<!DOCTYPE HTML>
<html lang="en" class="sidebar-visible no-js coal">
    <head>
        <!-- Book generated using mdBook -->
        <meta charset="UTF-8">
        <title>rust codewar - Andrew&#x27;s Blog</title>


        <!-- Custom HTML head -->
        
        <meta name="description" content="Andrew Ryan&#x27;s Blog">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="theme-color" content="#ffffff" />

        <link rel="icon" href="../../favicon.svg">
        <link rel="shortcut icon" href="../../favicon.png">
        <link rel="stylesheet" href="../../css/variables.css">
        <link rel="stylesheet" href="../../css/general.css">
        <link rel="stylesheet" href="../../css/chrome.css">

        <!-- Fonts -->
        <link rel="stylesheet" href="../../FontAwesome/css/font-awesome.css">
        <link rel="stylesheet" href="../../fonts/fonts.css">

        <!-- Highlight.js Stylesheets -->
        <link rel="stylesheet" href="../../highlight.css">
        <link rel="stylesheet" href="../../tomorrow-night.css">
        <link rel="stylesheet" href="../../ayu-highlight.css">

        <!-- Custom theme stylesheets -->
        <link rel="stylesheet" href="../../src/style/custom.css">

        <!-- MathJax -->
        <script async src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
    </head>
    <body>
    <div id="body-container">
        <!-- Provide site root to javascript -->
        <script>
            var path_to_root = "../../";
            var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "coal" : "coal";
        </script>

        <!-- Work around some values being stored in localStorage wrapped in quotes -->
        <script>
            try {
                var theme = localStorage.getItem('mdbook-theme');
                var sidebar = localStorage.getItem('mdbook-sidebar');

                if (theme.startsWith('"') && theme.endsWith('"')) {
                    localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
                }

                if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
                    localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
                }
            } catch (e) { }
        </script>

        <!-- Set the theme before any content is loaded, prevents flash -->
        <script>
            var theme;
            try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
            if (theme === null || theme === undefined) { theme = default_theme; }
            var html = document.querySelector('html');
            html.classList.remove('no-js')
            html.classList.remove('coal')
            html.classList.add(theme);
            html.classList.add('js');
        </script>

        <!-- Hide / unhide sidebar before it is displayed -->
        <script>
            var html = document.querySelector('html');
            var sidebar = null;
            if (document.body.clientWidth >= 1080) {
                try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
                sidebar = sidebar || 'visible';
            } else {
                sidebar = 'hidden';
            }
            html.classList.remove('sidebar-visible');
            html.classList.add("sidebar-" + sidebar);
        </script>

        <nav id="sidebar" class="sidebar" aria-label="Table of contents">
            <div class="sidebar-scrollbox">
                <ol class="chapter"><li class="chapter-item affix "><a href="../../index.html">Andrew's Blog</a></li><li class="chapter-item "><a href="../../posts/linux/linux.html"><strong aria-hidden="true">1.</strong> Linux</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/linux/install_linux.html"><strong aria-hidden="true">1.1.</strong> install linux</a></li><li class="chapter-item "><a href="../../posts/linux/bash_profile.html"><strong aria-hidden="true">1.2.</strong> bash profile</a></li><li class="chapter-item "><a href="../../posts/linux/command_list.html"><strong aria-hidden="true">1.3.</strong> command list</a></li><li class="chapter-item "><a href="../../posts/linux/git_guide.html"><strong aria-hidden="true">1.4.</strong> git guide</a></li><li class="chapter-item "><a href="../../posts/linux/tar.html"><strong aria-hidden="true">1.5.</strong> tar</a></li><li class="chapter-item "><a href="../../posts/Linux/git_cheatsheet.html"><strong aria-hidden="true">1.6.</strong> Git Cheatsheet</a></li><li class="chapter-item "><a href="../../posts/Linux/bash_cheatsheet.html"><strong aria-hidden="true">1.7.</strong> Bash Cheatsheet</a></li></ol></li><li class="chapter-item "><a href="../../posts/macos/mac.html"><strong aria-hidden="true">2.</strong> MacOS</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/macos/macos_profiles.html"><strong aria-hidden="true">2.1.</strong> macos profiles</a></li><li class="chapter-item "><a href="../../posts/macos/macos_pwn_env_setup.html"><strong aria-hidden="true">2.2.</strong> macos pwn env setup</a></li></ol></li><li class="chapter-item "><a href="../../posts/swift/swift.html"><strong aria-hidden="true">3.</strong> Swift</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/swift/learn_swift.html"><strong aria-hidden="true">3.1.</strong> learn swift basics</a></li><li class="chapter-item "><a href="../../posts/swift/swift_extensions.html"><strong aria-hidden="true">3.2.</strong> Swift extensions</a></li><li class="chapter-item "><a href="../../posts/swift/swiftui_extension.html"><strong aria-hidden="true">3.3.</strong> SwiftUI extensions</a></li><li class="chapter-item "><a href="../../posts/swift/install_swift.html"><strong aria-hidden="true">3.4.</strong> install swift</a></li><li class="chapter-item "><a href="../../posts/swift/task_planner.html"><strong aria-hidden="true">3.5.</strong> implment task panner app with SwiftUI</a></li><li class="chapter-item "><a href="../../posts/swift/swift_cheat_sheet.html"><strong aria-hidden="true">3.6.</strong> Swift Cheat Sheet</a></li><li class="chapter-item "><a href="../../posts/swift/yinci_url.html"><strong aria-hidden="true">3.7.</strong> Personal privacy protocol</a></li><li class="chapter-item "><a href="../../posts/swift/swift_regular_exressions.html"><strong aria-hidden="true">3.8.</strong> Swift regular exressions</a></li><li class="chapter-item "><a href="../../posts/ios/how_to_create_beautiful_ios_charts_in_swift.html"><strong aria-hidden="true">3.9.</strong> How to Create Beautiful iOS Charts in Swift</a></li><li class="chapter-item "><a href="../../posts/swift/swiftui_source_code.html"><strong aria-hidden="true">3.10.</strong> SwiftUI source code</a></li><li class="chapter-item "><a href="../../posts/swift/use_swift_fetch_iciba_api.html"><strong aria-hidden="true">3.11.</strong> use swift fetch iciba API</a></li></ol></li><li class="chapter-item "><a href="../../posts/ios/ios.html"><strong aria-hidden="true">4.</strong> iOS</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/ios/cocaposd_setup_and_install_for_ios_project.html"><strong aria-hidden="true">4.1.</strong> cocaposd setup and install for ios project</a></li><li class="chapter-item "><a href="../../posts/ios/swiftui_show_gif_image.html"><strong aria-hidden="true">4.2.</strong> SwiftUI show gif image</a></li><li class="chapter-item "><a href="../../posts/ios/implement_task_planner_app.html"><strong aria-hidden="true">4.3.</strong> implement Task planner App</a></li></ol></li><li class="chapter-item "><a href="../../posts/objective_c/objective_c.html"><strong aria-hidden="true">5.</strong> Objective-C</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/objective_c/objective_c_cheat_sheet.html"><strong aria-hidden="true">5.1.</strong> Objective-C Cheat Sheet</a></li><li class="chapter-item "><a href="../../posts/objective_c/objective_c_for_absolute_beginners_read_note.html"><strong aria-hidden="true">5.2.</strong> Objective-C Note</a></li></ol></li><li class="chapter-item "><a href="../../posts/dart/dart.html"><strong aria-hidden="true">6.</strong> Dart</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/dart/flutter.html"><strong aria-hidden="true">6.1.</strong> Flutter Cheat Sheet</a></li><li class="chapter-item "><a href="../../posts/dart/dart_cheat_sheet.html"><strong aria-hidden="true">6.2.</strong> Dart Cheat Sheet</a></li><li class="chapter-item "><a href="../../posts/flutter/flutter_dev_test.html"><strong aria-hidden="true">6.3.</strong> Flutter dev test</a></li></ol></li><li class="chapter-item "><a href="../../posts/rust/rust.html"><strong aria-hidden="true">7.</strong> Rust</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/rust/offline_use_rust.html"><strong aria-hidden="true">7.1.</strong> Offline use rust</a></li><li class="chapter-item "><a href="../../posts/rust/rust_grammer.html"><strong aria-hidden="true">7.2.</strong> rust grammar</a></li><li class="chapter-item "><a href="../../posts/rust/pase_string_and_decimal_conversion.html"><strong aria-hidden="true">7.3.</strong> pase string and decimal conversion</a></li><li class="chapter-item "><a href="../../posts/rust/parse_types.html"><strong aria-hidden="true">7.4.</strong> rust types</a></li><li class="chapter-item "><a href="../../posts/rust/rust_life_cycle.html"><strong aria-hidden="true">7.5.</strong> Rust life cycle</a></li><li class="chapter-item "><a href="../../posts/rust/rust_generic.html"><strong aria-hidden="true">7.6.</strong> rust generics</a></li><li class="chapter-item "><a href="../../posts/rust/rust_implment_matrix.html"><strong aria-hidden="true">7.7.</strong> Rust implement matrix</a></li><li class="chapter-item "><a href="../../posts/rust/rust_sort.html"><strong aria-hidden="true">7.8.</strong> Rust implement sort algorithms</a></li><li class="chapter-item "><a href="../../posts/rust/implement_aes_encryption.html"><strong aria-hidden="true">7.9.</strong> Rust implement AEC encryption and decryption</a></li><li class="chapter-item "><a href="../../posts/rust/implement_trie_data_structure.html"><strong aria-hidden="true">7.10.</strong> implement trie data structure</a></li><li class="chapter-item "><a href="../../posts/rust/rust_implement_tree.html"><strong aria-hidden="true">7.11.</strong> implement tree data_structure</a></li><li class="chapter-item "><a href="../../posts/rust/list_dir.html"><strong aria-hidden="true">7.12.</strong> list dir</a></li><li class="chapter-item "><a href="../../posts/rust/fast_way_to_implment_object_trait.html"><strong aria-hidden="true">7.13.</strong> fast way to implment object trait</a></li><li class="chapter-item "><a href="../../posts/rust/compress_rust_binary_size.html"><strong aria-hidden="true">7.14.</strong> compress rust binary size</a></li><li class="chapter-item "><a href="../../posts/rust/implment_file_upload_backend.html"><strong aria-hidden="true">7.15.</strong> impliment file upload</a></li><li class="chapter-item "><a href="../../posts/rust/this_is_add_post_cli_implementation_in_rust.html"><strong aria-hidden="true">7.16.</strong> this is add_post cli implementation in rust</a></li><li class="chapter-item "><a href="../../posts/rust/use_rust_implment_a_copyclipbord_cli.html"><strong aria-hidden="true">7.17.</strong> Use rust implment a copyclipbord CLI</a></li><li class="chapter-item "><a href="../../posts/rust/sqlite_database_add_delete_update_show_in_rust.html"><strong aria-hidden="true">7.18.</strong> sqlite database add delete update show in rust</a></li><li class="chapter-item "><a href="../../posts/rust/implementing_tokio_joinhandle_for_wasm.html"><strong aria-hidden="true">7.19.</strong> Implementing tokio JoinHandle for wasm</a></li><li class="chapter-item "><a href="../../posts/rust/rust_implement_a_crate_for_encode_and_decode_brainfuck_and_ook.html"><strong aria-hidden="true">7.20.</strong> rust implement a crate for encode and decode brainfuck and ook</a></li><li class="chapter-item "><a href="../../posts/rust/slint_builtin_elements.html"><strong aria-hidden="true">7.21.</strong> Slint Builtin Elements</a></li><li class="chapter-item "><a href="../../posts/rust/corporate_network_install_rust_on_windows.html"><strong aria-hidden="true">7.22.</strong> Corporate network install Rust on windows</a></li><li class="chapter-item "><a href="../../posts/rust/rust_binary_file_how_to_judge_static_link_or_dynamic_link_in_macos.html"><strong aria-hidden="true">7.23.</strong> rust binary file how to judge static link or dynamic link in Macos</a></li><li class="chapter-item "><a href="../../posts/rust/rust_binary_include_dir_and_get_contents.html"><strong aria-hidden="true">7.24.</strong> rust binary include dir and get contents</a></li><li class="chapter-item "><a href="../../posts/rust/how_to_create_yolov8_based_object_detection_web_service_using_python,_julia,_node.js,_javascript,_go_and_rust.html"><strong aria-hidden="true">7.25.</strong> How to create YOLOv8-based object detection web service using Python, Julia, Node.js, JavaScript, Go and Rust</a></li><li class="chapter-item "><a href="../../posts/rust/implment_builder_proc_macro_for_command_struct.html"><strong aria-hidden="true">7.26.</strong> implment Builder proc-macro for Command struct</a></li></ol></li><li class="chapter-item "><a href="../../posts/java/java.html"><strong aria-hidden="true">8.</strong> Java</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/java/java_grammar.html"><strong aria-hidden="true">8.1.</strong> java grammar and codewar</a></li><li class="chapter-item "><a href="../../posts/java/run_jar.html"><strong aria-hidden="true">8.2.</strong> java run .jar</a></li><li class="chapter-item "><a href="../../posts/java/java_pomxml_add_defaultgoal_to_build.html"><strong aria-hidden="true">8.3.</strong> Java pomxml add defaultGoal to build</a></li><li class="chapter-item "><a href="../../posts/java/java_set_mvn_mirror.html"><strong aria-hidden="true">8.4.</strong> Java set mvn mirror</a></li></ol></li><li class="chapter-item "><a href="../../posts/python/python.html"><strong aria-hidden="true">9.</strong> Python</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/python/convert_pesn.html"><strong aria-hidden="true">9.1.</strong> convert pesn</a></li><li class="chapter-item "><a href="../../posts/python/find_remove_dir.html"><strong aria-hidden="true">9.2.</strong> find and remove dir</a></li><li class="chapter-item "><a href="../../posts/python/timing_message.html"><strong aria-hidden="true">9.3.</strong> wechat send message</a></li><li class="chapter-item "><a href="../../posts/python/use_python_openpyxl_package_read_and_edit_excel_files.html"><strong aria-hidden="true">9.4.</strong> Use python openpyxl package read and edit excel files</a></li><li class="chapter-item "><a href="../../posts/python/sanctum_model_yaml.html"><strong aria-hidden="true">9.5.</strong> sanctum model yaml</a></li><li class="chapter-item "><a href="../../posts/python/how_to_detect_objects_on_images_using_the_yolov8_neural_network.html"><strong aria-hidden="true">9.6.</strong> How to detect objects on images using the YOLOv8 neural network</a></li><li class="chapter-item "><a href="../../posts/python/use_huggingface_model.html"><strong aria-hidden="true">9.7.</strong> use huggingface model</a></li></ol></li><li class="chapter-item "><a href="../../posts/go/go.html"><strong aria-hidden="true">10.</strong> Go</a></li><li class="chapter-item "><a href="../../posts/javascript/js.html"><strong aria-hidden="true">11.</strong> Javascript</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/javascript/js_tutorial.html"><strong aria-hidden="true">11.1.</strong> js tutorial</a></li><li class="chapter-item "><a href="../../posts/javascript/js_tutorial_map.html"><strong aria-hidden="true">11.2.</strong> ja map</a></li><li class="chapter-item "><a href="../../posts/javascript/js_tutorial_math.html"><strong aria-hidden="true">11.3.</strong> js math</a></li><li class="chapter-item "><a href="../../posts/javascript/js_tutorial_object.html"><strong aria-hidden="true">11.4.</strong> js object</a></li><li class="chapter-item "><a href="../../posts/javascript/js_tutorial_set.html"><strong aria-hidden="true">11.5.</strong> js set</a></li><li class="chapter-item "><a href="../../posts/javascript/single_thread_and_asynchronous.html"><strong aria-hidden="true">11.6.</strong> single thread and asynchronous</a></li><li class="chapter-item "><a href="../../posts/javascript/this.html"><strong aria-hidden="true">11.7.</strong> js this</a></li><li class="chapter-item "><a href="../../posts/javascript/js_implment_aes.html"><strong aria-hidden="true">11.8.</strong> js implment aes</a></li><li class="chapter-item "><a href="../../posts/javascript/getting_started_with_ajax.html"><strong aria-hidden="true">11.9.</strong> getting started with ajax</a></li><li class="chapter-item "><a href="../../posts/javascript/BinarySearchTree.html"><strong aria-hidden="true">11.10.</strong> binary search tree</a></li><li class="chapter-item "><a href="../../posts/javascript/goole_zx.html"><strong aria-hidden="true">11.11.</strong> goole zx</a></li><li class="chapter-item "><a href="../../posts/javascript/es6.html"><strong aria-hidden="true">11.12.</strong> es6</a></li></ol></li><li class="chapter-item "><a href="../../posts/ruby/ruby.html"><strong aria-hidden="true">12.</strong> Ruby</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/ruby/rails_setup_env.html"><strong aria-hidden="true">12.1.</strong> ruby on rails setup environment</a></li><li class="chapter-item "><a href="../../posts/ruby/learn_ruby.html"><strong aria-hidden="true">12.2.</strong> learn ruby</a></li><li class="chapter-item "><a href="../../posts/ruby/ruby_note.html"><strong aria-hidden="true">12.3.</strong> Ruby Note</a></li><li class="chapter-item "><a href="../../posts/ruby/setup_ruby_for_ctf.html"><strong aria-hidden="true">12.4.</strong> Setup ruby for CTF</a></li></ol></li><li class="chapter-item "><a href="../../posts/react/react.html"><strong aria-hidden="true">13.</strong> React</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/react/react_life_cycle.html"><strong aria-hidden="true">13.1.</strong> react life cycle</a></li><li class="chapter-item "><a href="../../posts/react/react_router.html"><strong aria-hidden="true">13.2.</strong> react router</a></li><li class="chapter-item "><a href="../../posts/react/react_this.html"><strong aria-hidden="true">13.3.</strong> react this</a></li><li class="chapter-item "><a href="../../posts/react/react_interviw.html"><strong aria-hidden="true">13.4.</strong> react interview</a></li><li class="chapter-item "><a href="../../posts/react/important_react_interview.html"><strong aria-hidden="true">13.5.</strong> important react interview</a></li><li class="chapter-item "><a href="../../posts/react/react_quick_reference.html"><strong aria-hidden="true">13.6.</strong> react quick reference</a></li><li class="chapter-item "><a href="../../posts/react/redux_quick_reference.html"><strong aria-hidden="true">13.7.</strong> redux quick reference</a></li></ol></li><li class="chapter-item "><a href="../../posts/vue/vue.html"><strong aria-hidden="true">14.</strong> Vue</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/vue/vue_ajax.html"><strong aria-hidden="true">14.1.</strong> vue ajax</a></li></ol></li><li class="chapter-item "><a href="../../posts/angular/angular.html"><strong aria-hidden="true">15.</strong> Angular</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/angular/controller_communication.html"><strong aria-hidden="true">15.1.</strong> controller communication</a></li><li class="chapter-item "><a href="../../posts/angular/creating_custom_directives.html"><strong aria-hidden="true">15.2.</strong> creating custom directives</a></li><li class="chapter-item "><a href="../../posts/angular/directive_notes.html"><strong aria-hidden="true">15.3.</strong> directive notes</a></li><li class="chapter-item "><a href="../../posts/angular/directive_communication.html"><strong aria-hidden="true">15.4.</strong> directive communication</a></li><li class="chapter-item "><a href="../../posts/angular/post_params.html"><strong aria-hidden="true">15.5.</strong> post params</a></li><li class="chapter-item "><a href="../../posts/angular/read_json_angular.html"><strong aria-hidden="true">15.6.</strong> read json angular</a></li><li class="chapter-item "><a href="../../posts/angular/same_route_reload.html"><strong aria-hidden="true">15.7.</strong> same route reload</a></li></ol></li><li class="chapter-item "><a href="../../posts/css/css.html"><strong aria-hidden="true">16.</strong> Css</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/css/use_css_media.html"><strong aria-hidden="true">16.1.</strong> use css media</a></li></ol></li><li class="chapter-item "><a href="../../posts/php/php.html"><strong aria-hidden="true">17.</strong> Php</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/php/for_php_string_implment_some_extemtion_functions.html"><strong aria-hidden="true">17.1.</strong> for php string implment some extemtion functions</a></li><li class="chapter-item "><a href="../../posts/php/php_cheatsheet.html"><strong aria-hidden="true">17.2.</strong> PHP cheatsheet</a></li></ol></li><li class="chapter-item "><a href="../../posts/windows/windows.html"><strong aria-hidden="true">18.</strong> Windows</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/windows/windows.html"><strong aria-hidden="true">18.1.</strong> Windows</a></li><li class="chapter-item "><a href="../../posts/windows/windows10_use_powershell_dedup_redundent_path.html"><strong aria-hidden="true">18.2.</strong> Windows10 use PowerShell dedup redundent PATH</a></li></ol></li><li class="chapter-item expanded "><a href="../../posts/leetcode/leetcode.html"><strong aria-hidden="true">19.</strong> Leetcode</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/leetcode/rust_leetcode.html"><strong aria-hidden="true">19.1.</strong> rust leetcode</a></li><li class="chapter-item expanded "><a href="../../posts/leetcode/rust_codewar.html" class="active"><strong aria-hidden="true">19.2.</strong> rust codewar</a></li><li class="chapter-item "><a href="../../posts/leetcode/swift_codewar.html"><strong aria-hidden="true">19.3.</strong> swift codewar</a></li><li class="chapter-item "><a href="../../posts/leetcode/js_leetcode.html"><strong aria-hidden="true">19.4.</strong> js leetcode</a></li><li class="chapter-item "><a href="../../posts/leetcode/java_leetcode.html"><strong aria-hidden="true">19.5.</strong> java leetcode</a></li><li class="chapter-item "><a href="../../posts/leetcode/rust_huawei.html"><strong aria-hidden="true">19.6.</strong> huawei test</a></li><li class="chapter-item "><a href="../../posts/leetcode/rust_utils.html"><strong aria-hidden="true">19.7.</strong> rust common functions</a></li><li class="chapter-item "><a href="../../posts/leetcode/olympiad_training.html"><strong aria-hidden="true">19.8.</strong> Computer olympiad training</a></li></ol></li><li class="chapter-item "><a href="../../posts/ctf/CTF.html"><strong aria-hidden="true">20.</strong> CTF</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/ctf/CTF_Note.html"><strong aria-hidden="true">20.1.</strong> CTF Note</a></li><li class="chapter-item "><a href="../../posts/ctf/0.1_Web.html"><strong aria-hidden="true">20.2.</strong> Web</a></li><li class="chapter-item "><a href="../../posts/ctf/4.1_Misc.html"><strong aria-hidden="true">20.3.</strong> Misc</a></li><li class="chapter-item "><a href="../../posts/ctf/3.2_PWN_note.html"><strong aria-hidden="true">20.4.</strong> PWN</a></li><li class="chapter-item "><a href="../../posts/ctf/3.1_Crypto.html"><strong aria-hidden="true">20.5.</strong> Crypto</a></li><li class="chapter-item "><a href="../../posts/ctf/3.4_RSA_note.html"><strong aria-hidden="true">20.6.</strong> Rsa attack</a></li><li class="chapter-item "><a href="../../posts/ctf/3.5_Base64.html"><strong aria-hidden="true">20.7.</strong> Base64</a></li><li class="chapter-item "><a href="../../posts/ctf/0.0_SQL Injection Cheatsheet.html"><strong aria-hidden="true">20.8.</strong> SQL Injection Cheatsheet</a></li><li class="chapter-item "><a href="../../posts/ctf/1.1_SQL_injection.html"><strong aria-hidden="true">20.9.</strong> SQL Injection</a></li><li class="chapter-item "><a href="../../posts/ctf/1.2_SQL_injection_UNION_attacks.html"><strong aria-hidden="true">20.10.</strong> SQL Injection UNION attacks</a></li><li class="chapter-item "><a href="../../posts/ctf/1.3_Blind SQL injection.html"><strong aria-hidden="true">20.11.</strong> Blind SQL Injection</a></li><li class="chapter-item "><a href="../../posts/ctf/1.4_Code Injection.html"><strong aria-hidden="true">20.12.</strong> Code Injection</a></li><li class="chapter-item "><a href="../../posts/ctf/1.5_SSRF.html"><strong aria-hidden="true">20.13.</strong> SSRF</a></li><li class="chapter-item "><a href="../../posts/ctf/1.6_OS command injection.html"><strong aria-hidden="true">20.14.</strong> OS command injection</a></li><li class="chapter-item "><a href="../../posts/ctf/1.7_Local file inclusion.html"><strong aria-hidden="true">20.15.</strong> Local file inclusion</a></li><li class="chapter-item "><a href="../../posts/ctf/1.8_Remote file inclusion.html"><strong aria-hidden="true">20.16.</strong> Remote file inclusion</a></li><li class="chapter-item "><a href="../../posts/ctf/1.9_CSRFm.html"><strong aria-hidden="true">20.17.</strong> CSRF</a></li><li class="chapter-item "><a href="../../posts/ctf/1.10_NoSQL injection.html"><strong aria-hidden="true">20.18.</strong> NoSQL injection</a></li><li class="chapter-item "><a href="../../posts/ctf/1.11_JSON injection.html"><strong aria-hidden="true">20.19.</strong> JSON injection</a></li><li class="chapter-item "><a href="../../posts/ctf/1.12_CTF_Web_SQL_Note.html"><strong aria-hidden="true">20.20.</strong> CTF Web SQL Note</a></li><li class="chapter-item "><a href="../../posts/ctf/2.1_XXE.html"><strong aria-hidden="true">20.21.</strong> XXE</a></li><li class="chapter-item "><a href="../../posts/ctf/2.2_XSS.html"><strong aria-hidden="true">20.22.</strong> XSS</a></li><li class="chapter-item "><a href="../../posts/ctf/2.3_Upload File.html"><strong aria-hidden="true">20.23.</strong> Upload File</a></li><li class="chapter-item "><a href="../../posts/ctf/2.4_serialize_unserialize.html"><strong aria-hidden="true">20.24.</strong> serialize unserialize</a></li><li class="chapter-item "><a href="../../posts/ctf/2.5_Race condition.html"><strong aria-hidden="true">20.25.</strong> Race condition</a></li><li class="chapter-item "><a href="../../posts/ctf/zip_plain_text_attack.html"><strong aria-hidden="true">20.26.</strong> Zip plain text attack</a></li><li class="chapter-item "><a href="../../posts/ctf/3.3_pwn HCTF2016 brop.html"><strong aria-hidden="true">20.27.</strong> pwn HCTF2016 brop</a></li><li class="chapter-item "><a href="../../posts/ctf/pwn_patch_defense_skill.html"><strong aria-hidden="true">20.28.</strong> PWN Patch defense skill</a></li><li class="chapter-item "><a href="../../posts/ctf/pwn_stack_overflow.html"><strong aria-hidden="true">20.29.</strong> PWN stack overflow</a></li><li class="chapter-item "><a href="../../posts/ctf/pwn_heap_overflow.html"><strong aria-hidden="true">20.30.</strong> PWN heap overflow</a></li><li class="chapter-item "><a href="../../posts/ctf/pwn_format_string_vulnerability.html"><strong aria-hidden="true">20.31.</strong> PWN Format String Vulnerability</a></li><li class="chapter-item "><a href="../../posts/ctf/kali_linux_tutorials.html"><strong aria-hidden="true">20.32.</strong> Kali linux tutorials</a></li><li class="chapter-item "><a href="../../posts/ctf/google_dorks_2023_lists.html"><strong aria-hidden="true">20.33.</strong> Google Dorks 2023 Lists</a></li><li class="chapter-item "><a href="../../posts/ctf/dvwa_writeup.html"><strong aria-hidden="true">20.34.</strong> DVWA WriteUp</a></li><li class="chapter-item "><a href="../../posts/ctf/bwapp_writeup.html"><strong aria-hidden="true">20.35.</strong> bWAPP WriteUp</a></li><li class="chapter-item "><a href="../../posts/ctf/sqlilabs_writeup.html"><strong aria-hidden="true">20.36.</strong> sqlilabs WriteUp</a></li><li class="chapter-item "><a href="../../posts/ctf/pwnable_kr_challenge.html"><strong aria-hidden="true">20.37.</strong> Solutions for pwnable.kr</a></li><li class="chapter-item "><a href="../../posts/ctf/the_periodic_table.html"><strong aria-hidden="true">20.38.</strong> The Periodic Table</a></li><li class="chapter-item "><a href="../../posts/ctf/pwntools_cheatsheet.html"><strong aria-hidden="true">20.39.</strong> Pwntools Cheatsheet</a></li><li class="chapter-item "><a href="../../posts/ctf/gdb_cheatsheet.html"><strong aria-hidden="true">20.40.</strong> GDB Cheatsheet</a></li></ol></li><li class="chapter-item "><a href="../../posts/iltes/iltes.html"><strong aria-hidden="true">21.</strong> ILTES</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/iltes/iltes_writing.html"><strong aria-hidden="true">21.1.</strong> ILTES Writing</a></li></ol></li></ol>
            </div>
            <div id="sidebar-resize-handle" class="sidebar-resize-handle"></div>
        </nav>

        <!-- Track and set sidebar scroll position -->
        <script>
            var sidebarScrollbox = document.querySelector('#sidebar .sidebar-scrollbox');
            sidebarScrollbox.addEventListener('click', function(e) {
                if (e.target.tagName === 'A') {
                    sessionStorage.setItem('sidebar-scroll', sidebarScrollbox.scrollTop);
                }
            }, { passive: true });
            var sidebarScrollTop = sessionStorage.getItem('sidebar-scroll');
            sessionStorage.removeItem('sidebar-scroll');
            if (sidebarScrollTop) {
                // preserve sidebar scroll position when navigating via links within sidebar
                sidebarScrollbox.scrollTop = sidebarScrollTop;
            } else {
                // scroll sidebar to current active section when navigating via "next/previous chapter" buttons
                var activeSection = document.querySelector('#sidebar .active');
                if (activeSection) {
                    activeSection.scrollIntoView({ block: 'center' });
                }
            }
        </script>

        <div id="page-wrapper" class="page-wrapper">

            <div class="page">
                                <div id="menu-bar-hover-placeholder"></div>
                <div id="menu-bar" class="menu-bar sticky">
                    <div class="left-buttons">
                        <button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
                            <i class="fa fa-bars"></i>
                        </button>
                        <button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
                            <i class="fa fa-paint-brush"></i>
                        </button>
                        <ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
                            <li role="none"><button role="menuitem" class="theme" id="light">Light</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
                        </ul>
                        <button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
                            <i class="fa fa-search"></i>
                        </button>
                    </div>

                    <h1 class="menu-title">Andrew&#x27;s Blog</h1>

                    <div class="right-buttons">
                        <a href="https://gitee.com/dnrops/dnrops" title="Git repository" aria-label="Git repository">
                            <i id="git-repository-button" class="fa fa-github"></i>
                        </a>

                    </div>
                </div>

                <div id="search-wrapper" class="hidden">
                    <form id="searchbar-outer" class="searchbar-outer">
                        <input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
                    </form>
                    <div id="searchresults-outer" class="searchresults-outer hidden">
                        <div id="searchresults-header" class="searchresults-header"></div>
                        <ul id="searchresults">
                        </ul>
                    </div>
                </div>

                <!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
                <script>
                    document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
                    document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
                    Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
                        link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
                    });
                </script>

                <div id="content" class="content">
                    <main>
                        <h1 id="codewar-rust-implementation"><a class="header" href="#codewar-rust-implementation">Codewar rust implementation</a></h1>
<h2 id="kata-1-vec-删除重复的元素返回-unique-vec"><a class="header" href="#kata-1-vec-删除重复的元素返回-unique-vec">Kata 1 (vec 删除重复的元素,返回 Unique Vec)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>use std::collections::BTreeSet;
fn unique_in_order(vec: Vec&lt;i32&gt;) -&gt; Vec&lt;i32&gt; {
            let mut bset = BTreeSet::new();
            for i in vec {
                bset.insert(i);
            }
            let mut re_vec = Vec::new();
            for item in &amp;bset {
                re_vec.push(*item);
            }
            re_vec
}

fn unique_in_order&lt;T&gt;(sequence: T) -&gt; Vec&lt;T::Item&gt;
    where
        T: std::iter::IntoIterator,
        T::Item: std::cmp::PartialEq + std::fmt::Debug,
    {
        let mut v: Vec&lt;_&gt; = sequence.into_iter().collect();
        v.dedup();
        v
    }
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-2-寻找-k-大元素删除重复"><a class="header" href="#kata-2-寻找-k-大元素删除重复">Kata 2 (寻找 k 大元素，删除重复)</a></h2>
<pre><pre class="playground"><code class="language-rust">/**
 * Kata1
 * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
 * @param a int整型一维数组
 * @param n int整型
 * @param K int整型     * @return int整型
 */
struct Kata1 {}
impl Kata1 {
    fn new() -&gt; Self {
        Kata1 {}
    }
    #[allow(non_snake_case)]
    #[allow(dead_code)]
    #[allow(unused_variables)]
    pub fn findKth(&amp;self, a: Vec&lt;i32&gt;, n: i32, K: i32) -&gt; i32 {
        // write code here
        use std::collections::BTreeSet;
        fn unique_in_order(vec: Vec&lt;i32&gt;) -&gt; Vec&lt;i32&gt; {
            let mut bset = BTreeSet::new();
            for i in vec {
                bset.insert(i);
            }
            let mut re_vec = Vec::new();
            for item in &amp;bset {
                re_vec.push(*item);
            }
            re_vec
        }
        let mut a_ = a.clone();
        a_ = unique_in_order(a_.clone());
        a_.sort();
        // dbg!(&amp;a_);
        // println!(&quot;{:?}&quot;, unique_in_order(a_.clone()));
        return a_[a_.len() - K as usize];
    }
}
fn main{
    println!(&quot;{}&quot;,Kata1::findKth(&amp;Kata1::new(),vec![1,5,14,65,2,5],6,3)); //return 5
}</code></pre></pre>
<h2 id="kata-3-三个数的最大乘积"><a class="header" href="#kata-3-三个数的最大乘积">Kata 3 (三个数的最大乘积)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>struct Solution{}
impl Solution {
    fn new() -&gt; Self {
        Solution{}
    }
    /**
    * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
    * 最大乘积
        * @param A int整型一维数组
        * @return long长整型
    */
    pub fn solve(&amp;self, A: Vec&lt;i32&gt;) -&gt; i64 {
   let mut vec = A;
    vec.sort();
    fn contain_minus(vec: Vec&lt;i32&gt;) -&gt; bool {
        let mut re = false;
        for i in vec {
            if i &lt; 0 {
                re = true;
            }
        }
        re
    }
    if contain_minus(vec.clone()) {
        if vec[0] as i64 * vec[1] as i64 &gt; vec[vec.len() - 2] as i64 * vec[vec.len() - 3] as i64 {
            return vec[vec.len() - 1] as i64 * vec[0] as i64 * vec[1] as i64;
        }
    }
    return vec[vec.len() - 1] as i64 * vec[vec.len() - 2] as i64 * vec[vec.len() - 3] as i64; }
}
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-4-排序算法的实现-sort-algorithm-in-rust"><a class="header" href="#kata-4-排序算法的实现-sort-algorithm-in-rust">Kata 4 (排序算法的实现 Sort Algorithm in Rust)</a></h2>
<pre><pre class="playground"><code class="language-rust">fn bubble_sort&lt;T&gt;(slice: &amp;mut [T])
where
    T: Ord,
{
    let mut swapped = true;
    while swapped {
        swapped = false;
        for i in 1..slice.len() {
            if slice[i - 1] &gt; slice[i] {
                slice.swap(i - 1, i);
                swapped = true;
            }
        }
    }
}

fn isertion_sort&lt;T&gt;(slice: &amp;mut [T])
where
    T: Ord,
{
    for unsorted in 1..slice.len() {
        let i = match slice[..unsorted].binary_search(&amp;slice[unsorted]) {
            Ok(i) =&gt; i,
            Err(err) =&gt; err,
        };
        slice[i..=unsorted].rotate_right(1);
    }
}

fn main() {
    let mut vec1 = vec![1, 2, 30, 40, 5, 6, 7];
    bubble_sort(&amp;mut vec1);
    assert_eq!(vec1, vec![1, 2, 5, 6, 7, 30, 40]);
    println!(&quot;buble_sort {:?}&quot;, vec1);

    let mut vec2 = vec![10, 2, 30, 40, 5, 6, 7];
    isertion_sort(&amp;mut vec2);
    assert_eq!(vec2, vec![2, 5, 6, 7, 10, 30, 40]);
    println!(&quot;isertion_sort {:?}&quot;, vec2);
}</code></pre></pre>
<h2 id="kata-5-最小移动次数每次操作-n-1-各元素加-1最终值相等"><a class="header" href="#kata-5-最小移动次数每次操作-n-1-各元素加-1最终值相等">Kata 5 (最小移动次数，每次操作 n-1 各元素加 1，最终值相等)</a></h2>
<pre><pre class="playground"><code class="language-rust">#[allow(dead_code)]
/**
 * 输入：nums = [1,2,3]
输出：3
解释：
只需要3次操作（注意每次操作会增加两个元素的值）：
[1,2,3]  =&gt;  [2,3,3]  =&gt;  [3,4,3]  =&gt;  [4,4,4]
*/
struct Solution {}
impl Solution {
    pub fn min_moves(nums: Vec&lt;i128&gt;) -&gt; i128 {
        nums.iter().sum::&lt;i128&gt;() - nums.iter().min().unwrap() * nums.len() as i128
    }
}
fn main() {
    println!(
        &quot;{}&quot;,
        Solution::min_moves(vec![11515115151, 100000000, 20000000000000000000000000])
    );
    println!(&quot;{}&quot;, Solution::min_moves(vec![1, 2, 3]));
}</code></pre></pre>
<h2 id="kata-6-vec-中所有类型转化为-string"><a class="header" href="#kata-6-vec-中所有类型转化为-string">Kata 6 (Vec 中所有类型转化为 String)</a></h2>
<pre><pre class="playground"><code class="language-rust">macro_rules! vec_strs {
    (
        $($element:expr),*
    ) =&gt; {
        {
            let mut v = Vec::new();
            $(
                v.push(format!(&quot;{}&quot;, $element));
            )*
            v
        }
    };
}
fn main() {
    let s = vec_strs![1, &quot;a&quot;, true, 3.14159f32];
    println!(&quot;{:?}&quot;, s); //[&quot;1&quot;, &quot;a&quot;, &quot;true&quot;, &quot;3.14159&quot;]
    assert_eq!(s, &amp;[&quot;1&quot;, &quot;a&quot;, &quot;true&quot;, &quot;3.14159&quot;]);
}</code></pre></pre>
<h2 id="kata-7--kmp-算法"><a class="header" href="#kata-7--kmp-算法">Kata 7 ( kmp 算法)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>/**
描述
给你一个文本串 T ，一个非空模板串 S ，问 S 在 T 中出现了多少次
数据范围：1 \le len(S) \le 500000, 1 \le len(T) \le 10000001≤len(S)≤500000,1≤len(T)≤1000000
要求：空间复杂度 O(len(S))O(len(S))，时间复杂度 O(len(S)+len(T))O(len(S)+len(T))
示例1
输入：
&quot;ababab&quot;,&quot;abababab&quot;
复制
返回值：
2
* */
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-8-数字的幂-i64pow2-as-u32"><a class="header" href="#kata-8-数字的幂-i64pow2-as-u32">Kata 8 (数字的幂 i64.pow(2 as u32))</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span>#![allow(unused_imports)]
#![allow(unused_macros)]
#![allow(dead_code)]
#![allow(unused_variables)]
<span class="boring">fn main() {
</span>use proconio::{input, marker::*};
use std::cmp::*;
use std::collections::*;

//solution for problem A
pub mod a {
    pub fn run() {
        proconio::input! {
            a: i32, b: i32
        }
        println!(&quot;{}&quot;, 32i64.pow((a - b) as u32))
    }
}
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-9-判断输入的两个字符串中的-chars-是否相同是-yes否-no"><a class="header" href="#kata-9-判断输入的两个字符串中的-chars-是否相同是-yes否-no">Kata 9 (判断输入的两个字符串中的 chars 是否相同，是-&gt;Yes，否-&gt;No)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span>#![allow(unused_imports)]
#![allow(unused_macros)]
#![allow(dead_code)]
#![allow(unused_variables)]
<span class="boring">fn main() {
</span>use proconio::{input, marker::*};
use std::cmp::*;
use std::collections::*;
//solution for problem B
pub mod b {
    pub fn run() {
        use proconio::{input, marker::*};
        input! {
            mut s: Chars,
            t: Chars,
        }
        if s.iter().zip(t.iter()).all(|(a, b)| a == b) {
            println!(&quot;Yes&quot;);
        } else {
            let mut f = false;
            for i in 0..s.len() - 1 {
                s.swap(i, i + 1);
                f |= s.iter().zip(t.iter()).all(|(a, b)| a == b);
                s.swap(i, i + 1);
            }
            if f {
                println!(&quot;Yes&quot;);
            } else {
                println!(&quot;No&quot;);
            }
        }
    }
}
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-10-select-mul把-string-分为二parse-以后相乘放到数组里-返回最大的-item"><a class="header" href="#kata-10-select-mul把-string-分为二parse-以后相乘放到数组里-返回最大的-item">Kata 10 (Select Mul,把 String 分为二，parse 以后相乘，放到数组里 返回最大的 item)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>/**
 * Sample Input 1
123
Sample Output 1
63
As described in Problem Statement, there are six ways to separate it:
12 and 3,
21 and 3,
13 and 2,
31 and 2,
23 and 1,
32 and 1.
The products of these pairs, in this order, are 36, 63, 26, 62, 23, 32, with 63 being the maximum.
 */
//solution for problem C
pub mod c {
    pub fn run() {
        use proconio::{input, marker::*};
        use std::collections::BTreeMap;
        input! {
            mut s: Chars,
        }
        //reverse
        fn reverse(phrase: String) -&gt; String {
            let mut i = phrase.len();
            let mut reversed = String::new();

            while i &gt; 0 {
                reversed.push(phrase.chars().nth(i - 1).unwrap());
                i -= 1;
            }
            reversed
        }
        let s = s.iter_mut().map(|x| x.to_string()).collect::&lt;Vec&lt;_&gt;&gt;();
        //generate bmap
        fn generate_bmap(s: Vec&lt;String&gt;) {
            let s_string = s.join(&quot;&quot;).to_string();
            let mut bmap: BTreeMap&lt;String, String&gt; = BTreeMap::new();
            for i in 1..s_string.len() {
                let mut s_string = s.clone().join(&quot;&quot;).to_string();
                let s_string_l = s_string.split_off(i);
                bmap.insert(s_string, s_string_l);
            }
            for i in 1..s_string.len() {
                let mut s_string = reverse(s.clone().join(&quot;&quot;).to_string());
                let s_string_l = s_string.split_off(i);
                bmap.insert(s_string, s_string_l);
            }
            let mut first_last_string = s.clone()[s.len() - 1].to_string();
            first_last_string.push_str(&amp;s.clone()[0].to_owned());

            let mut middle_string = String::new();
            for i in 1..s.len() - 1 {
                middle_string.push_str(&amp;s.clone()[i]);
            }
            bmap.insert(first_last_string, middle_string);

            let mut vec = vec![];
            for (v, k) in &amp;bmap {
                vec.push(
                    v.to_owned().parse::&lt;i128&gt;().unwrap() * k.to_owned().parse::&lt;i128&gt;().unwrap(),
                );
            }
            vec.sort();
            println!(&quot;{:?}&quot;, vec[vec.len() - 1]);
            // println!(&quot;{:?}&quot;, bmap);
            // println!(&quot;{:?}&quot;, vec);
        }

        generate_bmap(s.clone());
    }
}
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-11-online-games"><a class="header" href="#kata-11-online-games">Kata 11 (Online games)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>//https://atcoder.jp/contests/abc221/tasks/abc221_d

mod d {
    pub fn run() {
        proconio::input! {
            n: usize,
            ab: [(u32, u32); n],
        }
        let mut m = std::collections::BTreeMap::new();
        for (a, b) in ab {
            *m.entry(a).or_insert(0) += 1;
            *m.entry(a + b).or_insert(0) -= 1;
        }
        // println!(&quot;{:?}&quot;, m);
        let mut d = vec![0; n + 1]; //if n=5,[0, 0, 0, 0, 0, 0]
                                    // println!(&quot;{:?}&quot;, &amp;d);
        let mut p = 0;
        let mut k = 0;
        for (i, j) in m {
            d[k as usize] += i - p;
            p = i;
            k += j;
        }
        d.remove(0);
        println!(
            &quot;{:?}&quot;,
            d.iter_mut()
                .map(|x| x.to_string())
                .collect::&lt;Vec&lt;_&gt;&gt;()
                .join(&quot; &quot;)
        );
    }
}
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-12-快速开平方根倒数算法"><a class="header" href="#kata-12-快速开平方根倒数算法">Kata 12 (快速开平方根倒数算法)</a></h2>
<pre><pre class="playground"><code class="language-rust">#[allow(unused_macros)]
macro_rules! input {
    () =&gt; {{
        let mut string = String::new();
        std::io::stdin().read_line(&amp;mut string).unwrap();
        string = string.to_string().trim().to_owned();
        string
    }};
}
fn main() {
    let data: f64 = input!().parse::&lt;f64&gt;().unwrap();
    println!(&quot;{}&quot;, fast_sqrt64(data) * fast_sqrt64(data));
    println!(&quot;{}&quot;, 1.0 / f64::sqrt(16.0 * 16.0));
}

use std::mem;

/**
 * used to compute the 1/sqrt(x*x)
 */
fn fast_sqrt64(number: f64) -&gt; f64 {
    const MAGIC_U64: u64 = 0x5fe6ec85e7de30da;
    const THREEHALFS: f64 = 1.5;
    let x2: f64 = number * 0.5;
    let i: u64 = MAGIC_U64 - (unsafe { mem::transmute::&lt;f64, u64&gt;(number) } &gt;&gt; 1); // convert f64 to u64
    let y: f64 = unsafe { mem::transmute::&lt;u64, f64&gt;(i) }; // convert u64 to f64
    y * (THREEHALFS - (x2 * y * y))
}</code></pre></pre>
<h2 id="kata-13-生成和判断素数prime-number"><a class="header" href="#kata-13-生成和判断素数prime-number">Kata 13 (生成和判断素数，prime number)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>/** 生成素数*/
pub fn find_primes(n: usize) -&gt; Vec&lt;usize&gt; {
    let mut result = Vec::new();
    let mut is_prime = vec![true; n + 1];
    for i in 2..=n {
        if is_prime[i] {
            result.push(i);
        }
        ((i * 2)..=n).into_iter().step_by(i).for_each(|x| {
            is_prime[x] = false;
        });
    }
    result
}
/**判断是否素数 */
pub fn is_prime(n: u64) -&gt; bool {
        n == 2 || n % 2 &gt; 0 &amp;&amp; (3..=(n as f64).sqrt() as u64).step_by(2).all(|i| n % i &gt; 0)
}
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-14-vec-add-each"><a class="header" href="#kata-14-vec-add-each">Kata 14 (vec add each)</a></h2>
<pre><pre class="playground"><code class="language-rust">/**
 * Vec add each trait
 */
trait InIterator&lt;Type:Copy&gt;{
    fn each&lt;Function:Fn(Type) -&gt; Type&gt;(&amp;mut self,f:Function);
}
/**
 * each trait to Vec
 */
impl&lt;Type:Copy&gt; InIterator&lt;Type&gt; for Vec&lt;Type&gt;{
    fn each&lt;Function:Fn(Type) -&gt; Type&gt;(&amp;mut self,f:Function){
        let mut i = 0;
        while i &lt; self.len(){
            self[i] = f(self[i]);
            i+= 1;
        }
    }
}

fn main(){
    let mut v:Vec&lt;i128&gt;= vec![1,50,65,100];
    v.each(|x| x*9999999999999999999999999999999999);
    eprintln!(&quot;{:?}&quot;,v);
}</code></pre></pre>
<h2 id="kata-15-生成菱形-图"><a class="header" href="#kata-15-生成菱形-图">Kata 15 (生成菱形 *图)</a></h2>
<pre><pre class="playground"><code class="language-rust">/**
 * Examples
A size 3 diamond:

 *
***
 *
 生成菱形 *图
 */
mod diamond {
    pub fn print(n: i32) -&gt; Option&lt;String&gt; {
    if n &lt; 0 || n % 2 == 0 {
        return None;
    }

    let n = n as usize;
    let diamond = (1..=n)
        .chain((1..n).rev())
        .step_by(2)
        .map(|i| format!(&quot;{}{}\n&quot;, &quot; &quot;.repeat((n - i) / 2), &quot;*&quot;.repeat(i)))
        .collect();

    Some(diamond)
    }
}
fn main(){
    eprintln!(&quot;{}&quot;,diamond::print(3).unwrap());
}</code></pre></pre>
<h2 id="kata-16-找出-m-到-n-之间的-prime-number-存到-vec"><a class="header" href="#kata-16-找出-m-到-n-之间的-prime-number-存到-vec">Kata 16 (找出 m 到 n 之间的 prime number 存到 vec)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>/**
输入g,m,n
找出m到n之间的prime number 存到vec
vec中找出 任意两个数的差 ==g
输出这两个数Some(a,b)
*/
mod steps_in_primes{
    use std::convert::TryInto;
    pub fn step(g: i32, m: u64, n: u64) -&gt; Option&lt;(u64, u64)&gt; {
    // your code
    // let mut vec:Vec&lt;&gt; = find_primes(n as usize);
    let mut vec:Vec&lt;i128&gt; = vec![];
    for i in m..=n{
        if is_prime(i as i128){
            vec.push(i as i128);
        }
    }
    // eprintln!(&quot;{:?}&quot;,vec);
    let mut re:Vec&lt;i128&gt; = vec![];
    for i in 0..vec.len()-1 {
        for j in i+1..vec.len()-1 {
            if vec[j] -vec[i] == g.try_into().unwrap(){
                re.push(vec[i].try_into().unwrap());
                re.push(vec[j].try_into().unwrap());
            }
        }
    }
    // eprintln!(&quot;{:?}&quot;,re);
    if re.len()&lt;1{
        return None;
    }
    Some((re[0].try_into().unwrap(),re[1].try_into().unwrap()))
    }
    pub fn is_prime(n: i128) -&gt; bool {
        n == 2 || n % 2 &gt; 0 &amp;&amp; (3..=(n as f64).sqrt() as u64).step_by(2).all(|i| n % i as i128 &gt; 0)
    }
}

/**
输入g,m,n
找出m到n之间的prime number 存到vec
vec中找出 任意两个数的差 ==g
输出这两个数Some(a,b)
*/
mod steps_in_primes1{
    pub fn is_prime(p: u64) -&gt; bool {
      p &gt;= 2 &amp;&amp;
      (2..)
      .take_while(|q| q * q &lt;= p)
      .all(|q| p % q != 0)
    }
    pub fn step(g: i32, m: u64, n: u64) -&gt; Option&lt;(u64, u64)&gt; {
      (m..n)
      .map(|p| (p, p + g as u64))
      .filter(|&amp;(p0, p1)| is_prime(p0) &amp;&amp; is_prime(p1))
      .nth(0)
        }
}
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-17-分数相加-得到不可简化的分数"><a class="header" href="#kata-17-分数相加-得到不可简化的分数">Kata 17 （分数相加 ，得到不可简化的分数）</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>/**
 * 分数相加 ，得到不可简化的分数
 * in:vec![(1, 2), (1, 3), (1, 4)]
 * 1/2 + 1/3 +1/4 = 6/12+4/12+3/12
 * out:Some((13, 12))
 *
*/
mod irreducible_sum_of_rationals{
    pub fn gcd(a: i64, b: i64) -&gt; i64 {
        if b == 0 {
            a
        } else {
            gcd(b, a % b)
        }
    }

    pub fn sum_fracts(l: Vec&lt;(i64, i64)&gt;) -&gt; Option&lt;(i64, i64)&gt; {
        if l.len() == 0 {
            None
        } else {
            let res = l.iter().fold((0, 1), |acc, item| {
                // dbg!(&amp;acc,&amp;item);
                let n = acc.0 * item.1 + acc.1 * item.0;
                // dbg!(n);
                let d = acc.1 * item.1;
                // dbg!(d);
                let g = gcd(n, d);
                // dbg!(g);
                (n / g, d / g)
            });
            // eprintln!(&quot;{}/{}&quot;,res.0,res.1); //13/12
            Some(res)
        }
    }

}
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-18-最大公约数"><a class="header" href="#kata-18-最大公约数">Kata 18 (最大公约数)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>//最大公约数
   pub fn gcd(a: i64, b: i64) -&gt; i64 {
        if b == 0 {
            a
        } else {
            gcd(b, a % b)
        }
    }
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-19-最小公倍数"><a class="header" href="#kata-19-最小公倍数">Kata 19 (最小公倍数)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>//公式法求最小公倍数
pub fn lcm(a: i32,b: i32) -&gt; i32 {
    a*b/gcd(a,b)
}
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-20前-n-个-prime-number-的乘积"><a class="header" href="#kata-20前-n-个-prime-number-的乘积">Kata 20(前 n 个 prime number 的乘积)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>/**
 * in:n :usize
 * out：前n个prime number的乘积
 */

mod primorial_of_a_number{
    pub fn num_primorial(n: usize) -&gt; u64 {
        let mut vec = vec![];
        for i in 2..100{
            if is_prime(i as u64){
                vec.push(i);
            }
        }
        let mut count =0;
        let mut mul =1;
        for i in 0..vec.len(){
            mul*=vec[i];
            count += 1;
            if count==n{
                break;
            }
        }
        mul
    }
    pub fn is_prime(p: u64) -&gt; bool {
      p &gt;= 2 &amp;&amp;
      (2..)
      .take_while(|q| q * q &lt;= p)
      .all(|q| p % q != 0)
    }
}
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-21-丢番图方程--diophantine-equation"><a class="header" href="#kata-21-丢番图方程--diophantine-equation">Kata 21 (丢番图方程 , Diophantine Equation)</a></h2>
<pre><pre class="playground"><code class="language-rust">/**
 * 丢番图方程
 * Diophantine Equation
 * x2 - 4 * y2 = n
 https://www.codewars.com/kata/554f76dca89983cc400000bb/train/rust
 */
mod diophantine_equation{
    pub fn solequa(n: u64) -&gt; Vec&lt;(u64, u64)&gt; {
    let mut result = vec![];
    if n % 4 == 2 { return result; } // early bailout
    let rn = (n as f64).sqrt() as u64;
    for a in 1u64..rn+1 {
        let b = n/a;
        if b*a != n || (b-a) % 4 != 0 { continue; }
        let y = (b-a) / 4;
        let x = a + 2*y;
        result.push((x,y));
    }
    result
    }
}
fn main(){
    eprintln!(&quot;{:?}&quot;,diophantine_equation::solequa(5)); //[(3, 1)]
    eprintln!(&quot;{:?}&quot;,diophantine_equation::solequa(20)); //[(6, 2)]
}</code></pre></pre>
<h2 id="kata-22-convet_char_vec_string_vec"><a class="header" href="#kata-22-convet_char_vec_string_vec">Kata 22 (convet_char_vec_string_vec)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>fn convet_char_vec_string_vec(vec:Vec&lt;char&gt;)-&gt;Vec&lt;String&gt; {
                    let mut v = vec![];
                    for i in vec.iter() {
                        if !i.is_ascii_whitespace(){
                        let mut s = &quot;&quot;.to_string();
                        s.push(*i);
                        s.push_str(&quot; &quot;);
                        v.push(s);
                        }
                    }
                    v
}
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-23-assert-type-in-rust"><a class="header" href="#kata-23-assert-type-in-rust">Kata 23 (assert type in rust)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub mod rust_type_assert{
    pub fn run() {
        use std::any::Any;
        pub fn is_string(s: &amp;dyn Any)-&gt;&amp;str {
            if s.is::&lt;String&gt;() {
                return &quot;It's a string!&quot;;
            } else {
            return &quot;Not a string...&quot;;
            }
        }
        assert_eq!(is_string(&amp;&quot;aa&quot;),&quot;Not a string...&quot;);
        assert_eq!(is_string(&amp;&quot;aa&quot;.to_string()),&quot;It's a string!&quot;);

        pub fn is_i64(s: &amp;dyn Any)-&gt;&amp;str {
            if s.is::&lt;i64&gt;() {
                return &quot;It's a i64!&quot;;
            } else {
            return &quot;Not a i64...&quot;;
            }
        }
        assert_eq!(is_i64(&amp;12),&quot;Not a i64...&quot;);
        assert_eq!(is_i64(&amp;(12 as i64)),&quot;It's a i64!&quot;);

    }
}
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-24-casting-binary-float-to-integer-进制转换"><a class="header" href="#kata-24-casting-binary-float-to-integer-进制转换">Kata 24 (Casting binary float to integer 进制转换)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>/**
 * 10.0 (f32) == 01000001001000000000000000000000 (binary)
 * convert_to_i32(10.0) returns 1092616192 (i32)
 */
pub mod casting_binary_float_to_integer{
    // return binary representation as i32
    use std::cell::RefCell;
    pub fn convert_to_i32(f: f32) -&gt; i32 {
        let ff:RefCell&lt;f32&gt; = RefCell::new(f);
        // eprintln!(&quot;2进制：{:b}&quot;, 10);
        // eprintln!(&quot;{:?}&quot;,  ff.clone().borrow_mut().to_bits() as i32);
        // println!(&quot;8进制：{:o}&quot;, 10);
        // println!(&quot;16进制：{:x}&quot;, 10);
         ff.clone().borrow_mut().to_bits() as i32
    }
    #[cfg(test)]
    mod tests {
        use super::*;
        #[test]
        fn provided_tests() {
            assert_eq!(convert_to_i32(10.0), 1092616192);
            assert_eq!(convert_to_i32(f32::INFINITY), 0x7f800000);
            assert_eq!(convert_to_i32(1.40129846432e-44), 10);
        }
    }

}
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-25-cow-in-rust"><a class="header" href="#kata-25-cow-in-rust">Kata 25 (Cow in Rust)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>//Cow
    pub mod cow_demo{
        use std::borrow::Cow;
        pub fn run(){
            fn abs_all(input: &amp;mut Cow&lt;[i32]&gt;) {
                for i in 0..input.len() {
                    let v = input[i];
                    if v &lt; 0 {
                        input.to_mut()[i] = -v;
                    }
                }
            }
            let slice = [0, -31, 2];
            let mut input = Cow::from(&amp;slice[..]);
            abs_all(&amp;mut input);
            input.to_mut().push(-120);
            println!(&quot;to_mut {:?}&quot;, input);

            //use from
            let s = Cow::from(&quot;alen &quot;);
            println!(&quot;from {:?}&quot;, s.clone()+&quot;andry&quot;);
            println!(&quot;from {:?}&quot;, s.clone().to_string());

            //use to_owned
            use std::borrow::Borrow;
            let b = Cow::from(&quot;ops b!&quot;);
            let cow_borrow = Cow::to_owned(&amp;b);
            println!(&quot;cow_borrow: {:?}&quot;, cow_borrow.clone());

            //use from_iter
            use std::iter::FromIterator;
            let iter = Vec::from_iter([0,5,15].iter());
            let iter1 = Vec::from_iter((0..15).into_iter());
            let iter_cow = Cow::from_iter(iter);
            let iter_cow1 = Cow::from_iter(iter1.clone());
            println!(&quot;from_iter {:?}&quot;, iter_cow);
            println!(&quot;from_iter {:?}&quot;, iter_cow1);

            let find_7 = iter1.iter().find(|&amp;&amp;x| x == 7).unwrap();
            println!(&quot;iter1 include 7 : {:?}&quot;, *find_7==7);
        }}
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-26-cell-in-rust"><a class="header" href="#kata-26-cell-in-rust">Kata 26 (Cell in Rust)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>//Cell
    pub mod cell_demo{
        use std::cell::Cell;
        use std::cell::RefCell;
        struct Point{x:usize, y:usize,sum:Cell&lt;Option&lt;usize&gt;&gt;}

        impl Point {
            pub fn sum(&amp;self) -&gt; usize {
                match self.sum.get() {
                    Some(sum) =&gt; {
                        println!(&quot;{}&quot;,sum);
                        sum
                    },
                    None =&gt; {
                        let new_sum = self.x+self.y;
                        self.sum.set(Some(new_sum));
                        println!(&quot;sum set: {:?}&quot;,new_sum);
                        new_sum
                    }
                }
            }
        }
        pub fn run() {
            let p = Point{x:8,y:16,sum:Cell::new(None)};
            println!(&quot;{}&quot;,p.sum());
            println!(&quot;{}&quot;,p.sum());
        }
    }
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-27-refcell-in-rust"><a class="header" href="#kata-27-refcell-in-rust">Kata 27 (RefCell in Rust)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span> //RefCell
    pub mod refcell_demo{
        use std::cell::RefCell;
        struct Point{x:usize, y:usize,sum:RefCell&lt;Option&lt;usize&gt;&gt;}
        impl Point {
            pub fn sum(&amp;self) -&gt; usize {
                match self.sum.take() {
                    Some(sum) =&gt; {
                        println!(&quot;{}&quot;,sum);
                        sum
                    },
                    None =&gt; {
                        let new_sum = self.x+self.y;
                        self.sum.replace(Some(new_sum));
                        println!(&quot;sum set: {:?}&quot;,new_sum);
                        new_sum
                    }
                }
            }
        }
        pub fn run() {
            let p = Point{x:8,y:16,sum:RefCell::new(None)};
            println!(&quot;{}&quot;,p.sum());
            println!(&quot;{}&quot;,p.sum());
            use std::cell::RefCell;

            let c1 = RefCell::new(5);
            let ptr = c1.as_ptr();
            println!(&quot;{:?}&quot;,ptr);

            let mut c2 = RefCell::new(5);
            *c2.get_mut() += 1;
            assert_eq!(c2, RefCell::new(6));
            println!(&quot;{:?}&quot;,c2);
            println!(&quot;before take:{:?}&quot;,c2.take());
            println!(&quot;after take:{:?}&quot;,c2.take());
            println!(&quot;after take:{:?}&quot;,c2.take());
            println!(&quot;after take:{:?}&quot;,c2.take());
            let mut cc = *c2.borrow_mut();
            cc+=0;
            println!(&quot;{:?}&quot;,cc);
        }
    }
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-28-impl-drop-trait-in-rust"><a class="header" href="#kata-28-impl-drop-trait-in-rust">Kata 28 (impl Drop trait in Rust)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub mod drop_demo{
        struct Person{
            name: String,
        }
        impl Drop for Person{
            fn drop(&amp;mut self) {
                println!(&quot;drop:{}&quot;,self.name);
            }
        }
        pub fn run(){
            let _alen = Person{name: &quot;Alen&quot;.into()};
            let _andry = Person{name: &quot;Andry&quot;.into()};
            eprintln!(&quot;{},{}&quot;,_alen.name,_andry.name);
        }
    }
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-29-每-n-个位组合存到-hashset-中已存的值重复的话-return-false"><a class="header" href="#kata-29-每-n-个位组合存到-hashset-中已存的值重复的话-return-false">Kata 29 (每 n 个位组合存到 HashSet 中,已存的值重复的话 return false)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>/**
 * https://www.codewars.com/kata/60aee6ae617c26004717d257/solutions
 */
#[allow(dead_code)]
#[allow(unused_variables)]
pub mod de_bruijn_sequences{
    use std::collections::HashSet;
    pub fn de_bruijn_sequence(sequence: &amp;str, n: usize) -&gt; bool {
        let mut vec_sequence: Vec&lt;u8&gt; = sequence.bytes().collect();
        vec_sequence.extend(vec_sequence[..n - 1].to_vec());
        eprintln!(&quot;{:?}&quot;,vec_sequence);

        let mut seen: HashSet&lt;Vec&lt;u8&gt;&gt; = HashSet::new();
        for i in 0..sequence.len() {
            if !seen.insert(vec_sequence[i..(i + n)].to_vec()) {
                return false;
            }
        }
        //每n个位组合存到HashSet中,已存的值重复的话return false
        eprintln!(&quot;{:?}&quot;,seen);
        true
    }
    #[cfg(test)]
    mod tests {
    use super::*;
    #[test]
    fn sample_tests() {
        assert_eq!(de_bruijn_sequence(&quot;0011&quot;, 2), true);//01，00，11，10
        assert_eq!(de_bruijn_sequence(&quot;abcd&quot;, 2), true);
        assert_eq!(de_bruijn_sequence(&quot;0101&quot;, 2), false);
        assert_eq!(de_bruijn_sequence(&quot;11231&quot;, 2), false);
        assert_eq!(de_bruijn_sequence(&quot;aabca&quot;, 3), true);
        assert_eq!(de_bruijn_sequence(&quot;00000111011010111110011000101001&quot;, 5), true);
        assert_eq!(de_bruijn_sequence(&quot;11111000001110110011010001001010&quot;, 5), true);
        assert_eq!(de_bruijn_sequence(&quot;0011123302031321&quot;, 2), false);
        }
    }

}
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-30-很大数的乘积和很大数的幂"><a class="header" href="#kata-30-很大数的乘积和很大数的幂">Kata 30 (很大数的乘积和很大数的幂)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>/**
 * power function for large numbers,multiply large numbers
 * 很大数的乘积和很大数的幂
 */
#[allow(dead_code)]
#[allow(unused_variables)]
#[allow(unused_mut)]
pub mod power_function_for_large_numbers{
    pub fn power(a:String, b:String) -&gt; String {
        let mut s = a.clone();
        for i in 0..b.parse::&lt;i32&gt;().unwrap()-1 {
            // println!(&quot;{}&quot;,s);
            s=mul(s.clone(),a.clone());
        }
        fn mul(a:String,aa:String)-&gt; String {
            multiply_large_numbers(a.clone(),aa.clone())
        }
        s
    }
    pub fn multiply_large_numbers(num1:String, num2:String)-&gt;String{
        let len1 = num1.len();
        let len2 = num2.len();
        let num1_str:Vec&lt;i32&gt; = num1.split(&quot;&quot;)
                .filter(|s| !s.is_empty())
                .collect::&lt;Vec&lt;_&gt;&gt;().iter().map(|s| s.parse::&lt;i32&gt;().unwrap()).collect();
        let num2_str:Vec&lt;i32&gt; = num2.split(&quot;&quot;)
                .filter(|s| !s.is_empty())
                .collect::&lt;Vec&lt;_&gt;&gt;().iter().map(|s| s.parse::&lt;i32&gt;().unwrap()).collect();

        if len1 == 0 || len2 == 0 {
            return &quot;0&quot;.into();
        }
        let mut  result:Vec&lt;i32&gt; = &quot;0&quot;.repeat(len1+len2).split(&quot;&quot;)
                .filter(|s| !s.is_empty())
                .collect::&lt;Vec&lt;_&gt;&gt;().iter()
                .map(|s| s.parse::&lt;i32&gt;().unwrap()).collect();
        let mut i_n1 = 0;
        let mut i_n2 = 0;
        for i in 0..len1{
            let ii = len1-i-1;
            let mut carry = 0;
            let mut n1 = num1_str[ii];
            let mut i_n2 = 0;
            for j in 0..len2{
                let jj = len2-j-1;
                let mut n2 = num2_str[jj];
                let mut summ = n1 * n2 + result[i_n1 + i_n2] + carry;
                let carry = summ;
                let sum_i_n = i_n1+i_n2;
                result[sum_i_n] = summ % 10;
                i_n2 += 1;
            }
             if carry &gt; 0{
                result[i_n1 + i_n2] += carry
             }
            i_n1 += 1;
        }
        let mut i:i32 = result.len() as i32 - 1;
        while i&gt;=0 &amp;&amp; result[i as usize] == 0{
            i -= 1
        }
        if i == -1{
            return &quot;0&quot;.into()
        }
        let mut s:String = &quot;&quot;.into();
        while i &gt;= 0{
            s.push_str(&amp;result[i as usize].to_string());
            i -= 1;
        }
        return s
    }

    #[cfg(test)]
    mod tests {
        use super::*;
        #[test]
        fn test_power() {
            assert_eq!(power(String::from(&quot;10&quot;),String::from(&quot;7&quot;)),&quot;10000000&quot;);
        }
    }
}
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-31-merge-two-vec-and-return-median-number"><a class="header" href="#kata-31-merge-two-vec-and-return-median-number">Kata 31 (Merge Two Vec and Return median number)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub mod mearge_two_vec_return_median{
    use std::convert::TryInto;
    pub fn mearge_vec&lt;T:Clone+Ord&gt;(a:Vec&lt;T&gt;,b:Vec&lt;T&gt;) -&gt; T
    where
    T: std::ops::Add&lt;Output = T&gt;+Ord+Clone+Copy+std::ops::Div&lt;Output = T&gt;+std::convert::Into&lt;T&gt;+From&lt;i32&gt;,
    {
        let mut a = a.clone();
        for item in b.iter() {
            a.push(*item);
        }
        a.sort();
        let l = a.len();
        if l%2 !=0 {
        let mid = a.len()/2;
        let mid_num = a[mid];
        return mid_num;
        }else{
        let mid = a.len()/2;
        let mid_num = a[mid]+a[mid-1];
        return mid_num.into() /2.into();
        }
    }
}
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-32-string-add-split_to_vec-tarit"><a class="header" href="#kata-32-string-add-split_to_vec-tarit">Kata 32 (String add split_to_vec tarit)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub mod string_add_trait{
    trait SplitToVec{
        fn split_to_vec(self,word:String)-&gt;Vec&lt;String&gt;;
    }
    impl SplitToVec for String{
        fn split_to_vec(self,word:String)-&gt;Vec&lt;String&gt;{
            let v = self.split(&amp;word).filter(|s|!s.is_empty()).collect::&lt;Vec&lt;&amp;str&gt;&gt;();
            v.iter().map(|s| s.to_string()).collect::&lt;Vec&lt;_&gt;&gt;()
        }
    }
    pub fn run_string(){
        let s = String::from(&quot;name: alen andry&quot;);
        let v = s.split_to_vec(&quot; &quot;.into()); //[&quot;name:&quot;, &quot;alen&quot;, &quot;andry&quot;]
        println!(&quot;{:?}&quot;, v);
    }
}
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-33-字符串中字符的出现次数统计"><a class="header" href="#kata-33-字符串中字符的出现次数统计">Kata 33 (字符串中字符的出现次数统计)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>// code war problems url :https://www.codewars.com/kata/57a6633153ba33189e000074/train/rust
// Example:
// ordered_count(&quot;abracadabra&quot;) == vec![('a', 5), ('b', 2), ('r', 2), ('c', 1), ('d', 1)]
#[allow(dead_code)]
#[allow(unused_variables)]
#[allow(unused_mut)]
use std::collections::BTreeMap;
fn ordered_count(sip: &amp;str) -&gt; Vec&lt;(char, i32)&gt; {
    let sip = sip.to_owned();
    let set_sip = sip.clone();
    let mut arr_sip: Vec&lt;char&gt; = set_sip.chars().collect();
    arr_sip.sort();
    arr_sip.reverse();
    // println!(&quot;{:?}&quot;, arr_sip);
    let mut bmap = BTreeMap::new();
    for x in arr_sip {
        bmap.insert(x, count_x_in_sip(&amp;sip, x));
    }
    // println!(&quot;{:?}&quot;, bmap);
    fn count_x_in_sip(sip: &amp;str, target: char) -&gt; i32 {
        let mut c: i32 = 0;
        for x in sip.chars() {
            if target == x {
                c += 1;
            }
        }
        return c;
    }
    // bmap to tuple vec
    fn convert_bmap_to_vec(bmap: BTreeMap&lt;char, i32&gt;) -&gt; Vec&lt;(char, i32)&gt; {
        let mut vec = vec![];
        for (v, k) in &amp;bmap {
            vec.push((v.to_owned(), k.to_owned()));
        }
        return vec;
    }
    return convert_bmap_to_vec(bmap);
}
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-34-find-most-common-element-找出出现次数最多的元素"><a class="header" href="#kata-34-find-most-common-element-找出出现次数最多的元素">Kata 34 (find most common element 找出出现次数最多的元素)</a></h2>
<pre><pre class="playground"><code class="language-rust">fn main() {
    /*{&quot;a&quot;: 2, &quot;b&quot;: 3, &quot;m&quot;: 1, &quot;s&quot;: 3}
    common item val :&quot;b&quot;
    common item index :1
    common item val :&quot;s&quot;
    common item index :3
    */
    let str = &quot;aabbbssms&quot;;
    fn find_most_common(str: &amp;str) -&gt; [(&amp;str, i32); 1] {
        let mut bmap = BTreeMap::new();
        let str_vec = str.split(&quot;&quot;).filter(|s| !s.is_empty()).collect::&lt;Vec&lt;_&gt;&gt;();
        for i in 0..str_vec.len() {
            if !bmap.contains_key(str_vec[i]) {
                bmap.insert(str_vec[i], 1);
            } else {
                let mut count = bmap
                    .get(str_vec[i])
                    .unwrap()
                    .to_string()
                    .parse::&lt;i32&gt;()
                    .unwrap();
                count += 1;
                bmap.insert(str_vec[i], count);
            }
        }
        fn find_max&lt;I&gt;(iter: I) -&gt; Option&lt;I::Item&gt;
        where
            I: Iterator,
            I::Item: Ord,
        {
            iter.reduce(|a, b| if a &gt;= b { a } else { b })
        }
        println!(&quot;{:?}&quot;, bmap);
        // println!(&quot;{:?}&quot;, bmap.keys());
        // println!(&quot;{:?}&quot;, bmap.values());
        for (index, item) in bmap.values().enumerate() {
            if item == find_max(bmap.values()).unwrap() {
                let vec: Vec&lt;&amp;str&gt; = bmap.keys().cloned().collect();
                println!(&quot;common item val :{:?}&quot;, vec[index]);
                println!(&quot;common item index :{:?}&quot;, index);
            }
        }
        // println!(&quot;{:?}&quot;, find_max(bmap.values()).unwrap());
        return [(&quot;&quot;, find_max(bmap.values()).unwrap().to_owned())];
    }
    find_most_common(str);
}</code></pre></pre>
<h2 id="kata-35-sort-float-vec-从小到大-排序"><a class="header" href="#kata-35-sort-float-vec-从小到大-排序">Kata 35 (Sort float Vec 从小到大 排序)</a></h2>
<pre><pre class="playground"><code class="language-rust">fn main() {
    //sort 从小到大 排序
    let mut vec = vec![100.1, 1.15, 5.5, 1.123, 2.0];
    vec.sort_by(|a, b| a.partial_cmp(b).unwrap());
    println!(&quot;{:?}&quot;, vec);
    assert_eq!(vec, vec![1.123, 1.15, 2.0, 5.5, 100.1]);
}</code></pre></pre>
<h2 id="kata-36-slice-string-use-input-read-string"><a class="header" href="#kata-36-slice-string-use-input-read-string">Kata 36 (slice String, use input!() read string)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>#[allow(unused_variables)]
        fn slice_string(in_string: String, start: i32, end: i32) -&gt; String {
            let mut s = Vec::new();
            let in_string_vec = in_string
                .split(&quot;&quot;)
                .filter(|s| !s.is_empty())
                .collect::&lt;Vec&lt;_&gt;&gt;();
            if start &lt; 0 &amp;&amp; end &gt; in_string_vec.len() as i32 {
                return &quot;out of range&quot;.to_owned();
            } else {
                for i in start..end {
                    s.push(in_string_vec[i as usize]);
                }
            }
            return s.join(&quot;&quot;).to_string();
        }
<span class="boring">}</span></code></pre></pre>
<h2 id="自己定义的-input-快速-io-输入值"><a class="header" href="#自己定义的-input-快速-io-输入值">自己定义的 input!() (快速 IO 输入值)</a></h2>
<pre><pre class="playground"><code class="language-rust">#[allow(unused_macros)]
macro_rules! input {
    () =&gt; {{
        let mut string = String::new();
        std::io::stdin().read_line(&amp;mut string).unwrap();
        string
    }};
}
fn main() {
    let s = input!();
    println!(&quot;{:?}&quot;, s); //&quot;alen andry\n&quot;
    assert_eq!(&quot;alen andry\n&quot;.to_string(), s);
}</code></pre></pre>
<h2 id="kata-37-输出-string-的全排序"><a class="header" href="#kata-37-输出-string-的全排序">Kata 37 (输出 String 的全排序)</a></h2>
<pre><pre class="playground"><code class="language-rust">  // input '123' 输出string的全排序
  // [&quot;1&quot;, &quot;12&quot;, &quot;123&quot;, &quot;2&quot;, &quot;23&quot;, &quot;3&quot;]
pub mod c {
    pub fn run() {
        use proconio::{input, marker::*};
        input! {
            mut s: Chars,
        }
        let s = s.iter_mut().map(|x| x.to_string()).collect::&lt;Vec&lt;_&gt;&gt;();
        // println!(&quot;{:?}&quot;, s);
        #[allow(unused_variables)]
        fn slice_string(in_string: String, start: i32, end: i32) -&gt; String {
            let mut s = Vec::new();
            let in_string_vec = in_string
                .split(&quot;&quot;)
                .filter(|s| !s.is_empty())
                .collect::&lt;Vec&lt;_&gt;&gt;();
            if start &lt; 0 &amp;&amp; end &gt; in_string_vec.len() as i32 {
                return &quot;out of range&quot;.to_owned();
            } else {
                for i in start..end {
                    s.push(in_string_vec[i as usize]);
                }
            }
            return s.join(&quot;&quot;).to_string();
        }
        // let some_string = slice_string(s_string, 0, 3);
        // println!(&quot;{:?}&quot;, some_string);
        let s_string = s.join(&quot;&quot;).to_string();
        let mut out_vec = Vec::new();
        for i in 0..s.len() + 1 {
            for j in i + 1..s.len() + 1 {
                out_vec.push(slice_string(s_string.clone(), i as i32, j as i32));
            }
        }
        println!(&quot;{:?}&quot;, out_vec);
        // input '123' 输出string的全排序
        // [&quot;1&quot;, &quot;12&quot;, &quot;123&quot;, &quot;2&quot;, &quot;23&quot;, &quot;3&quot;]
    }
}

fn main() {
    c::run();
}</code></pre></pre>
<h2 id="kata-38-各位相加到小于-9-时输出合"><a class="header" href="#kata-38-各位相加到小于-9-时输出合">Kata 38 (各位相加到小于 9 时输出合)</a></h2>
<pre><pre class="playground"><code class="language-rust">/*
各位相加到小于9 时输出
imput 15 -&gt;6
imput 19 -&gt;1
imput 238 -&gt;4
*/

pub mod c {
    pub fn run() {
        use proconio::{input, marker::*};
        input! {
            mut s: Chars,
        }
        let s = s
            .iter_mut()
            .map(|x| x.to_string().parse::&lt;i32&gt;().unwrap())
            .collect::&lt;Vec&lt;_&gt;&gt;();
        // println!(&quot;{:?}&quot;, s);
        fn count(arr: Vec&lt;i32&gt;) -&gt; i32 {
            let mut sum = 0;
            for i in 0..arr.len() {
                sum += arr[i];
            }
            if sum &lt;= 9 {
                println!(&quot;{:?}&quot;, sum);
            } else {
                let arr = sum
                    .to_string()
                    .chars()
                    .map(|x| x.to_string().parse::&lt;i32&gt;().unwrap())
                    .collect::&lt;Vec&lt;_&gt;&gt;();
                // println!(&quot;{:?}&quot;, arr);
                count(arr);
            }
            return 0;
        }
        count(s);
    }
}


fn main() {
    c::run();
}</code></pre></pre>
<h2 id="kata-39-选择排序-slection_sort"><a class="header" href="#kata-39-选择排序-slection_sort">Kata 39 (选择排序 slection_sort)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>#[allow(dead_code)]
// code war problems url :https://www.codewars.com/kata/5861d28f124b35723e00005e/train/rust
pub fn slection_sort(arr: &amp;Vec&lt;i32&gt;) -&gt; Vec&lt;i32&gt; {
    // write code here
    let length = arr.len();
    let mut arr = arr.to_owned();
    let mut minindex;
    let mut temp;
    for i in 0..length - 1 {
        minindex = i;
        for j in i + 1..length {
            if arr[j] &lt; arr[minindex] {
                minindex = j;
            }
        }
        temp = arr[i];
        arr[i] = arr[minindex];
        arr[minindex] = temp;
    }
    return arr;
}
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-40-vec-中删除重复的部分"><a class="header" href="#kata-40-vec-中删除重复的部分">Kata 40 (vec 中删除重复的部分)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>#[allow(dead_code)]
#[allow(unused_variables)]
#[allow(unused_mut)]

pub fn run() {
    fn unique_in_order&lt;T&gt;(sequence: T) -&gt; Vec&lt;T::Item&gt;
    where
        T: std::iter::IntoIterator,
        T::Item: std::cmp::PartialEq + std::fmt::Debug,
    {
        let mut v: Vec&lt;_&gt; = sequence.into_iter().collect();
        v.dedup();
        v
    }
    let data = vec![&quot;A&quot;, &quot;A&quot;, &quot;B&quot;, &quot;b&quot;, &quot;b&quot;, &quot;b&quot;];
    let data2 = &quot;AAAABBBCCDAABBB&quot;.chars();
    println!(&quot;{:?}&quot;, unique_in_order(data));   //[&quot;A&quot;, &quot;B&quot;, &quot;b&quot;]
    println!(&quot;{:?}&quot;, unique_in_order(data2));  //['A', 'B', 'C', 'D', 'A', 'B']
}
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-41-rust-implement-fib-function-"><a class="header" href="#kata-41-rust-implement-fib-function-">Kata 41 (Rust implement fib function )</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub fn run() {
    //produce fib
    fn product_fib(prod: u64) {
        // your code
        let mut p: i64 = prod as i64;
        fn fib(n: u64) -&gt; u64 {
            match n {
                0 =&gt; 1,
                1 =&gt; 1,
                _ =&gt; fib(n - 1) + fib(n - 2),
            }
        }
        let mut list: Vec&lt;u64&gt; = Vec::new();
        while p &gt; -1 {
            list.push(fib(p as u64));
            p -= 1;
        }
        println!(&quot;{:?}&quot;, list);
    }
    product_fib(8); //produce 8 number
}
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-42-lettcode-two_sum-problem-solution-in-rust"><a class="header" href="#kata-42-lettcode-two_sum-problem-solution-in-rust">Kata 42 (Lettcode two_sum problem solution in rust)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>use std::collections::HashMap;

pub fn run(){
        fn two_sum(nums: Vec&lt;i32&gt;,taget:i32)-&gt; Vec&lt;i32&gt;{
            let mut h_map = HashMap::new();
            for i in 0..nums.len(){
                if let Some(&amp;j) = h_map.get(&amp;(taget-nums[i])){
                    return vec![j as i32,i as i32];
                }
                else{
                    h_map.insert(nums[i],i);
                }
            }
            vec![]
        }
        let result = two_sum(vec![1,2,0,2],2);
        println!(&quot;{:?}&quot;,result);

}
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-43-use-mutex-多线程共享一个值"><a class="header" href="#kata-43-use-mutex-多线程共享一个值">Kata 43 (Use mutex 多线程共享一个值)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub mod mutex {
    pub fn run() {
        use std::sync::Mutex;
        let l: &amp;'static _ = Box::leak(Box::new(Mutex::new(0.0)));
        let handlers = (0..999)
            .map(|_| {
                std::thread::spawn(move || {
                    for _ in 0..9999 {
                        *l.lock().unwrap() += 0.0001;
                    }
                })
            })
            .collect::&lt;Vec&lt;_&gt;&gt;();
        for handler in handlers {
            handler.join().unwrap();
        }
        assert_eq!(*l.lock().unwrap(), 999.0 * 9999.0);
    }
}
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-44-implment-default-for-type"><a class="header" href="#kata-44-implment-default-for-type">Kata 44 (implment default for type)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub mod implment_default {
    struct Grounded;
    impl Default for Grounded {
        fn default() -&gt; Self {Grounded}
    }
    struct Launched;
    // and so on
    struct Rocket&lt;Stage = Grounded&gt; {
        stage: std::marker::PhantomData&lt;Stage&gt;,
    }
    impl Default for Rocket&lt;Grounded&gt;
    where
        Grounded:Default,
    {
        fn default() -&gt; Self {
            Rocket{stage:std::marker::PhantomData}
        }
    }
    impl Rocket&lt;Grounded&gt; {
        pub fn launch(self) -&gt; Rocket&lt;Launched&gt; {
            Rocket{stage:std::marker::PhantomData}
        }
    }
    impl Rocket&lt;Launched&gt; {
        pub fn accelerate(&amp;mut self) {}
        pub fn decelerate(&amp;mut self) {}
    }
    struct Color;
    struct Kilograms;

    impl&lt;Stage&gt; Rocket&lt;Stage&gt; {
        pub fn color(&amp;self) -&gt; Color {Color}
        pub fn weight(&amp;self) -&gt; Kilograms {Kilograms}
    }
}
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-45-use-cow"><a class="header" href="#kata-45-use-cow">Kata 45 (Use Cow)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>#[allow(unused)]
pub mod use_cow {
    use std::borrow::Cow;
    use std::sync::Arc;
    fn test(ref a: String) {
        eprintln!(&quot;{:?}&quot;, a);
    }
    fn test1(v: &amp;mut Vec&lt;&amp;str&gt;) {
        v.push(&quot;z&quot;);
        v.push(&quot;x&quot;);
        v.push(&quot;y&quot;);
        for item in v.splitn(3, |s| *s == &quot;x&quot;) {
            println!(&quot;split:  {:?}&quot;, item);
        }
        v.reverse();
        eprintln!(&quot;{:?}&quot;, v);
    }

    pub fn run() {
        let s = String::from(&quot;ok&quot;);
        test(Cow::from(&amp;s).clone().to_string());
        eprintln!(&quot;{:?}&quot;, s);

        let mut v = vec![&quot;a&quot;, &quot;b&quot;];
        test1(&amp;mut Cow::from(&amp;v).clone().to_vec());
        v.sort();
        eprintln!(&quot;{:?}&quot;, v.join(&amp;&quot; &quot;));
        eprintln!(&quot;{:?}&quot;, v);
    }
}
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-46-二维vec-sort_by_row"><a class="header" href="#kata-46-二维vec-sort_by_row">Kata 46 (二维Vec sort_by_row)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub fn sort_by_row(arr: Vec&lt;Vec&lt;f64&gt;&gt;,row:usize) -&gt; Vec&lt;Vec&lt;f64&gt;&gt; {
        // write code here
        let length = arr[row].len();
        let mut arr = arr.to_owned();
        let mut minindex;
        for i in 0..length - 1 {
            minindex = i;
            for j in i + 1..length {
                if arr[row][j] &gt; arr[row][minindex] {
                    minindex = j;
                }
            }
            for k in 0..row+1{
                arr[k].swap(minindex,i);
            }
        }
        return arr;
    }
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-47-implement-clonal-selection-algorithm"><a class="header" href="#kata-47-implement-clonal-selection-algorithm">Kata 47 (<em>Implement clonal selection algorithm</em>)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub mod clonal_selection_algorithm {
    use rand::{thread_rng, Rng};
    pub fn y(a: f64, b: f64) -&gt; f64 {
        let aa = -30.0 * f64::powf(b, 4.0);
        let bb = 64.0 * f64::powf(b, 3.0);
        let cc = 43.8 * f64::powf(b, 2.0);
        let dd = 10.8 * f64::powf(b, 1.0);
        let ee = (aa + bb + cc + dd) * 1000.0 * f64::sin(5.0 * std::f64::consts::PI * a);
        let ff = 1.0 + 0.1 * f64::powf(a, 2.0);
        f64::abs(ee / ff)
    }
    pub fn cloning_number(beta: f64, population_number: f64, i: f64) -&gt; f64 {
        f64::floor((beta * population_number) / i)
    }
    pub fn generate_three_random(population_number: i32) -&gt; Vec&lt;Vec&lt;f64&gt;&gt; {

        fn generate() -&gt; f64 {
            let mut rng = thread_rng();
            let m: f64 = rng.gen_range(0.0..1.0);
            m
        }
        let mut temp: Vec&lt;f64&gt; = Vec::new();
        let mut temp2: Vec&lt;f64&gt; = Vec::new();
        let mut temp_fitness: Vec&lt;f64&gt; = Vec::new();
        for i in 0..population_number as usize {
            temp.push(generate());
            temp2.push(generate());
            temp_fitness.push(y(temp[i], temp2[i]));
        }
        vec![temp, temp2, temp_fitness]
    }
    pub fn sort_by_row(arr: Vec&lt;Vec&lt;f64&gt;&gt;,row:usize) -&gt; Vec&lt;Vec&lt;f64&gt;&gt; {
        // write code here
        let length = arr[row].len();
        let mut arr = arr.to_owned();
        let mut minindex;
        for i in 0..length - 1 {
            minindex = i;
            for j in i + 1..length {
                if arr[row][j] &gt; arr[row][minindex] {
                    minindex = j;
                }
            }
            for k in 0..row+1{
                arr[k].swap(minindex,i);
            }
        }
        return arr;
    }
    pub fn mutaition(clon: Vec&lt;&amp;Vec&lt;f64&gt;&gt;, theta: f64) -&gt; Vec&lt;Vec&lt;f64&gt;&gt; {
        fn generate() -&gt; f64 {
            let mut rng = thread_rng();
            let m: f64 = rng.gen_range(0.0..1.0);
            m
        }
        let mut mutation = vec![];
        let clon = clon;
        let mut clon1: Vec&lt;Vec&lt;f64&gt;&gt; = vec![];

        let len_clon = clon.len();
        for _ in 0..len_clon {
            let mut vec = vec![];
            for _ in 0..clon[0].len() {
                vec.push(generate());
            }
            mutation.push(vec.clone());
            clon1.push(vec.clone());
        }
        for i in 0..mutation.len() {
            for j in 0..mutation[0].len() {
                    clon1[i][j] = clon[i][j];
            }
        }
        for i in 0..mutation.len() {
            for j in 0..mutation[0].len() {
                if mutation[i][j] &lt; theta {
                    clon1[i][j] = generate();
                }
            }
        }
        let mut yy = vec![];
        for j in 0..clon1[0].len() {
            yy.push(y(clon1.clone()[0][j],clon1.clone()[1][j]));
        }
        clon1.push(yy);
        clon1
    }

    #[allow(unused)]
    pub fn run() {
        let mut iteration_number: i32 = 2;
        let mut population_number: i32 = 4;
        let mut n: usize = 10;
        let mut beta: f64 = 5.0;
        let mut theta: f64 = 0.2;
        let population = generate_three_random(population_number);
        let mut selected_population: Vec&lt;f64&gt; = vec![];
        let new_population = sort_by_row(population.clone(),2);
        let selected_population = vec![&amp;new_population[0], &amp;new_population[1]];
        // println!(&quot;population {:#?}&quot;, population.clone());
        // println!(&quot;new_population {:#?}&quot;, new_population.clone());
        // println!(&quot;selected_population {:#?}&quot;, selected_population.clone());
        let clone: Vec&lt;&amp;Vec&lt;f64&gt;&gt; = selected_population.clone();
        let new_clone = new_population.clone();
        let last_population = new_clone.clone();
        // println!(&quot;clone:{:#?}&quot;, &amp;clone);
        // println!(&quot;new_clone:{:#?}&quot;, &amp;new_clone);
        // println!(&quot;new_clone:{:#?}&quot;, &amp;last_population);
        let mutationed = mutaition(clone.clone(), theta);
        println!(&quot;mutationed:{:#?}&quot;, &amp;mutationed);
        let mut sorted_mutation = sort_by_row(mutationed.clone(),2).to_owned();
        println!(&quot;sorted_mutation:{:#?}&quot;, &amp;sorted_mutation);
    }
}
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-48-implement-coin_change-problem-还钱问题"><a class="header" href="#kata-48-implement-coin_change-problem-还钱问题">Kata 48 (<em>Implement coin_change problem</em> 还钱问题)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub mod coin_change{
    pub fn solution(coins:Vec&lt;i32&gt;,amount:i32)-&gt;i32{
        let mut max = amount+1;
        let mut dp = (0..max).map(|_|{amount+1}).collect::&lt;Vec&lt;_&gt;&gt;();
        dp[0]=0;
        for i in 1..=amount as usize{
            for j in 0..coins.len(){
                if coins[j] as usize &lt;= i{
                    dp[i]=std::cmp::min(dp[i], dp[i-coins[j] as usize]+1);
                }
            }
        }
        let mut re:i32;
        if dp[amount as usize]&gt;amount{
            re = -1;
        }else{
            re = dp[amount as usize];
        }
        println!(&quot;{:?}&quot;, &amp;dp);
        println!(&quot;{:?}&quot;, &amp;re);
        re
    }
    pub fn run(){
        solution(vec![2], 3);//-1
        solution(vec![1,2,5], 11); //3
    }
}
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-49-use-atomic-implement-mutex"><a class="header" href="#kata-49-use-atomic-implement-mutex">Kata 49 (use Atomic implement mutex)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub mod implement_mutex {
    #[allow(dead_code)]
    #[allow(unused)]
    use std::cell::UnsafeCell;
    use std::sync::atomic::{AtomicBool, Ordering};
    const LOCKED: bool = true;
    const UNLOCKED: bool = false;
    pub struct Mutex&lt;T&gt; {
        locked: AtomicBool,
        v: UnsafeCell&lt;T&gt;,
    }

    impl&lt;T&gt; Mutex&lt;T&gt; {
        fn new(t: T) -&gt; Self {
            Self {
                locked: AtomicBool::new(UNLOCKED),
                v: UnsafeCell::new(t),
            }
        }
        fn with_lock&lt;R&gt;(&amp;self, f: impl FnOnce(&amp;mut T) -&gt; R) -&gt; R {
            while self
                .locked
                .compare_exchange(UNLOCKED, LOCKED, Ordering::Acquire, Ordering::Acquire)
                .is_err()
            {
                while self.locked.load(Ordering::Relaxed) == LOCKED {
                    std::thread::yield_now();
                }
                std::thread::yield_now();
            }
            // self.locked.store(LOCKED,Ordering::Relaxed);
            let ret = f(unsafe { &amp;mut *self.v.get() });
            self.locked.store(UNLOCKED, Ordering::Release);
            ret
        }
    }
    unsafe impl&lt;T&gt; Sync for Mutex&lt;T&gt; where T: Send {}
    unsafe impl&lt;T&gt; Send for Mutex&lt;T&gt; where T: Send {}
    pub fn thread_handlers() {
        let l: &amp;'static _ = Box::leak(Box::new(Mutex::new(0)));

        let handlers = (0..999)
            .map(|_| {
                std::thread::spawn(move || {
                    for _ in 0..999 {
                        l.with_lock(|v| {
                            *v += 1;
                        });
                    }
                })
            })
            .collect::&lt;Vec&lt;_&gt;&gt;();

        for handler in handlers {
            handler.join().unwrap();
        }
        assert_eq!(l.with_lock(|v| *v), 999 * 999);
    }
    pub fn atomic_demo() {
        use std::sync::atomic::AtomicUsize;
        let x: &amp;'static _ = Box::leak(Box::new(AtomicBool::new(false)));
        let y: &amp;'static _ = Box::leak(Box::new(AtomicBool::new(false)));
        let z: &amp;'static _ = Box::leak(Box::new(AtomicUsize::new(0)));

        let _tx = std::thread::spawn(move || {
            x.store(true, Ordering::SeqCst);
        });
        let _ty = std::thread::spawn(move || {
            y.store(true, Ordering::SeqCst);
        });
        let t1 = std::thread::spawn(move || {
            while !x.load(Ordering::Acquire) {
                if y.load(Ordering::Acquire) {
                    z.fetch_add(1, Ordering::Release);
                }
            }
        });

        let t2 = std::thread::spawn(move || {
            while !y.load(Ordering::Acquire) {
                if x.load(Ordering::Acquire) {
                    z.fetch_add(1, Ordering::Release);
                }
            }
        });

        t1.join().unwrap();
        t2.join().unwrap();

        let z = z.load(Ordering::SeqCst);
        eprintln!(&quot;{:?}&quot;, z);
    }

    pub fn run() {
        // thread_handlers();
        atomic_demo();
    }
}
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-50-cmd_download_files"><a class="header" href="#kata-50-cmd_download_files">Kata 50 (cmd_download_files)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>#[allow(dead_code)]
#[allow(unused)]
#[allow(non_snake_case)]
pub mod cmd_download_files {
    use std::io::{self, Write};
    use std::process::Command;
    use std::sync::Mutex;
    pub fn download_all() {
        let pdfs: Vec&lt;Vec&lt;&amp;str&gt;&gt; = vec![vec![
&quot;https://projecteuclid.org/download/pdf_1/euclid.ss/1028905930&quot;,
  &quot;https://otr.cypherpunks.ca/otr-wpes.pdf&quot;, &quot;https://fahrplan.events.ccc.de/congress/2009/Fahrplan/attachments/1435_JTAG.pdf&quot;,
  &quot;https://philpapers.org/archive/RAATOR-2.pdf&quot;,
  &quot;https://www.usenix.org/system/files/sec20-sugawara.pdf&quot;,
]
];
        use std::thread::JoinHandle;
        fn download&lt;'a&gt;(url: &amp;'static str) {
            std::fs::create_dir_all(&quot;./pdfs&quot;);
            if url.contains(&quot;.pdf&quot;) {
                Command::new(&quot;duma&quot;)
                    .current_dir(&quot;./pdfs&quot;)
                    .arg(&quot;-c&quot;)
                    .arg(&quot;-n&quot;)
                    .arg(&quot;1000&quot;)
                    .arg(&quot;-T&quot;)
                    .arg(&quot;10&quot;)
                    .arg(url)
                    .spawn()
                    .expect(&quot;command failed to start&quot;);
            }
        }

        let l: &amp;'static _ = Box::leak(Box::new(Mutex::new(pdfs.clone())));

        for item in pdfs.iter() {
            for item1 in item.iter() {
                download(item1);
            }
        }
        println!(&quot;{}&quot;, &quot;download started&quot;);
    }
    pub fn make_zip() {
        fn zip(zip_name: &amp;str, name: &amp;str) {
            Command::new(&quot;zip&quot;)
                .current_dir(&quot;./&quot;)
                .arg(&quot;-r&quot;)
                .arg(zip_name)
                .arg(name)
                .spawn()
                .expect(&quot;sh command failed to start&quot;);
            println!(&quot;ok&quot;);
        }
        zip(&quot;pdfs.zip&quot;, &quot;./pdfs&quot;);
        // std::process::exit(1);
    }

    pub fn run() {
        download_all();
        make_zip();
    }
}
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-51-rgb-to-hex-conversion"><a class="header" href="#kata-51-rgb-to-hex-conversion">Kata 51 (RGB To Hex Conversion)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>#[allow(dead_code)]
#[allow(unused)]
#[allow(non_snake_case)]
pub mod rgb_to_hex {

    pub fn rgb(r: i32, g: i32, b: i32) -&gt; String {
        fn to_x(i: i32) -&gt; String {
            let mut result = String::new();
            if i &lt; 0 {
                result = String::from(&quot;00&quot;)
            } else if i &gt; 255 {
                result = String::from(&quot;FF&quot;)
            } else {
                if format!(&quot;{:x}&quot;, i).len() &lt;= 1 {
                    let mut re = String::from(&quot;0&quot;);
                    re.push_str(&amp;format!(&quot;{:x}&quot;, i).to_uppercase());
                    result = re;
                } else {
                    result = format!(&quot;{:x}&quot;, i).to_uppercase();
                }
            }
            result
        }
        format!(&quot;{}{}{}&quot;, to_x(r), to_x(g), to_x(b))
    }
    //another solution
    fn rgb_1(r: i32, g: i32, b: i32) -&gt; String {
        format!(
            &quot;{:02X}{:02X}{:02X}&quot;,
            r.clamp(0, 255),
            g.clamp(0, 255),
            b.clamp(0, 255)
        )
    }

    pub fn run() {
        assert_eq!(rgb(255, 255, 255), &quot;FFFFFF&quot;.to_string());
        assert_eq!(rgb(0, 0, 0), &quot;000000&quot;.to_string());
        assert_eq!(rgb(-20, 275, 125), &quot;00FF7D&quot;.to_string());
        assert_eq!(300.clamp(0, 255), 255);
    }
}
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-52-the-look-and-say-sequence"><a class="header" href="#kata-52-the-look-and-say-sequence">Kata 52 (The Look and Say sequence)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>/***
 * The Look and Say sequence
 * https://www.codewars.com/kata/5263c5d011f4233c9d000561/train/rust
*/
#[allow(dead_code)]
#[allow(unused)]
#[allow(non_snake_case)]
pub mod look_and_say_sequence {
    use itertools::{iterate, Itertools};

    fn get_lines(n: usize) -&gt; String {
        iterate(&quot;1&quot;.to_owned(), |s| {
            format!(
                &quot;{}&quot;,
                s.chars()
                    .dedup_with_count()
                    .format_with(&quot;&quot;, |(k, x), f| f(&amp;format_args!(&quot;{}{}&quot;, k, x)))
            )
        })
        .take(n)
        .join(&quot;,&quot;)
    }
    fn dedup_with_counts() {
        //根基前后相同的元素进行count
        use itertools::Itertools;

        let data = vec!['a', 'a', 'b', 'c', 'c', 'b', 'b'];
        itertools::assert_equal(
            data.into_iter().dedup_with_count(),
            vec![(2, 'a'), (1, 'b'), (2, 'c'), (2, 'b')],
        );
    }
    pub fn run() {
        println!(&quot;{:?}&quot;, get_lines(5));
        println!(&quot;{:?}&quot;, get_lines(8));
    }
    #[cfg(test)]
    mod tests {
        use super::*;
        #[test]
        fn basic() {
            assert_eq!(get_lines(2), &quot;1,11&quot;);
            assert_eq!(get_lines(3), &quot;1,11,21&quot;);
            assert_eq!(get_lines(5), &quot;1,11,21,1211,111221&quot;);
        }
    }
}
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-53-molecule-to-atoms-已知化学式-返回每个化学元素的数量"><a class="header" href="#kata-53-molecule-to-atoms-已知化学式-返回每个化学元素的数量">Kata 53 (Molecule to atoms 已知化学式 返回每个化学元素的数量)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>/**
 * Molecule to atoms 已知化学式 返回每个化学元素的数量
 * https://www.codewars.com/kata/52f831fa9d332c6591000511/train/rust
 * For example:
parse_molecule(&quot;H2O&quot;);           // water
// Ok([(&quot;H&quot;, 2), (&quot;O&quot;, 1)])

parse_molecule(&quot;Mg(OH)2&quot;);       // magnesium hydroxide
// Ok([(&quot;Mg&quot;, 1), (&quot;O&quot;, 2), (&quot;H&quot;, 2)]

parse_molecule(&quot;K4[ON(SO3)2]2&quot;); // Fremy's salt
// Ok([(&quot;K&quot;, 4), (&quot;O&quot;, 14),(&quot;N&quot;, 2),(&quot;S&quot;, 4)])

parse_molecule(&quot;pie&quot;)
// Err(ParseError)
 */
#[allow(dead_code)]
#[allow(unused)]
#[allow(non_snake_case)]
pub mod molecule_to_atoms {
    use std::collections::HashMap;
    use thiserror::Error;

    pub type Atom = (String, usize);
    pub type Molecule = Vec&lt;Atom&gt;;

    #[derive(Error, Debug)]
    pub enum ParseError {
        #[error(&quot;Not a valid molecule&quot;)]
        InvalidName,
        #[error(&quot;Mismatched parenthesis&quot;)]
        ParensMismatch,
    }

    fn atom(s: &amp;mut &amp;[u8]) -&gt; Atom {
        let mut i = 1;
        // dbg!(s.clone()[i] as char);
        while i &lt; s.len() &amp;&amp; s[i].is_ascii_lowercase() {
            //if second letter is lowercase i+=1
            i += 1;
        }
        //from 0..i if the atom name
        let name = std::str::from_utf8(&amp;s[..i]).unwrap().to_string();
        // dbg!(&amp;name);
        let end = i;

        while i &lt; s.len() &amp;&amp; s[i].is_ascii_digit() {
            i += 1;
        }
        let count = if i - end &gt; 0 {
            let count = std::str::from_utf8(&amp;s[end..i]).unwrap().parse().unwrap();
            count
        } else {
            1
        };
        *s = &amp;s[i..];
        (name, count)
    }

    fn parse_subsequence(s: &amp;mut &amp;[u8], output: &amp;mut Molecule) -&gt; Result&lt;(), ParseError&gt; {
        let opening = s[0];
        *s = &amp;s[1..];
        let seq_begin = output.len();
        parse_sequence(s, output)?;
        let seq_end = output.len();

        let mut i = 1;
        while i &lt; s.len() &amp;&amp; s[i].is_ascii_digit() {
            i += 1;
        }
        let count = if i &gt; 1 {
            let count = std::str::from_utf8(&amp;s[1..i]).unwrap().parse().unwrap();
            // dbg!(&amp;count);
            count
        } else {
            1
        };

        if i &gt; s.len() {
            return Err(ParseError::ParensMismatch);
        }
        if opening == b'(' &amp;&amp; s[0] != b')' {
            return Err(ParseError::ParensMismatch);
        }
        if opening == b'[' &amp;&amp; s[0] != b']' {
            return Err(ParseError::ParensMismatch);
        }
        if opening == b'{' &amp;&amp; s[0] != b'}' {
            return Err(ParseError::ParensMismatch);
        }
        *s = &amp;s[i..];
        for i in seq_begin..seq_end {
            output[i].1 *= count;
        }
        Ok(())
    }

    fn parse_sequence(s: &amp;mut &amp;[u8], output: &amp;mut Molecule) -&gt; Result&lt;(), ParseError&gt; {
        loop {
            if s.is_empty() {
                break;
            }

            let peek = s[0];
            dbg!(peek.clone() as char);
            if peek.is_ascii_uppercase() {
                let atom = atom(s);
                output.push(atom)
            } else if peek.is_ascii_lowercase() {
                return Err(ParseError::InvalidName);
            } else if matches!(peek, b'(' | b'[' | b'{') {
                parse_subsequence(s, output)?
            } else {
                break;
            }
        }
        Ok(())
    }

    pub fn parse_molecule(s: &amp;str) -&gt; Result&lt;Molecule, ParseError&gt; {
        let mut s = s.as_bytes();
        // dbg!(&amp;s);
        let mut molecules = vec![];
        parse_sequence(&amp;mut s, &amp;mut molecules)?;

        let mut molecule_map = HashMap::new();
        for (name, count) in molecules {
            *molecule_map.entry(name).or_insert(0) += count;
        }
        dbg!(&amp;molecule_map);
        Ok(molecule_map.into_iter().collect())
    }
    pub fn run() {
        parse_molecule(&quot;H2O&quot;);
        parse_molecule(&quot;Ca(OH)2&quot;);
        parse_molecule(&quot;CaO&quot;);
    }
    #[cfg(test)]
    mod tests {
        use super::{parse_molecule, Molecule};
        macro_rules! assert_parse {
            ($formula:expr, $expected:expr, $name:ident) =&gt; {
                #[test]
                fn $name() {
                    super::assert_parse($formula, &amp;$expected, &quot;&quot;);
                }
            };
        }
        mod molecules {
            assert_parse!(&quot;H&quot;, [(&quot;H&quot;, 1)], hydrogen);
            assert_parse!(&quot;O2&quot;, [(&quot;O&quot;, 2)], oxygen);
            assert_parse!(&quot;H2O&quot;, [(&quot;H&quot;, 2), (&quot;O&quot;, 1)], water);
            assert_parse!(
                &quot;Mg(OH)2&quot;,
                [(&quot;Mg&quot;, 1), (&quot;O&quot;, 2), (&quot;H&quot;, 2)],
                magnesium_hydroxide
            );
            assert_parse!(
                &quot;K4[ON(SO3)2]2&quot;,
                [(&quot;K&quot;, 4), (&quot;O&quot;, 14), (&quot;N&quot;, 2), (&quot;S&quot;, 4)],
                fremys_salt
            );
        }

        #[test]
        fn errors() {
            assert_fail(&quot;pie&quot;, &quot;Not a valid molecule&quot;);
            assert_fail(&quot;Mg(OH&quot;, &quot;Mismatched parenthesis&quot;);
            assert_fail(&quot;Mg(OH}2&quot;, &quot;Mismatched parenthesis&quot;);
        }

        fn assert_fail(formula: &amp;str, msg: &amp;str) {
            let result = parse_molecule(formula);
            assert!(
                result.is_err(),
                &quot;expected {} {:?} to fail, got {:?}&quot;,
                msg,
                formula,
                result.unwrap()
            );
        }

        fn assert_parse(formula: &amp;str, expected: &amp;[(&amp;str, usize)], _mst: &amp;str) {
            let mut expected = expected
                .into_iter()
                .map(|&amp;(name, usize)| (name.to_owned(), usize))
                .collect::&lt;Molecule&gt;();
            let result = parse_molecule(formula);
            assert!(
                result.is_ok(),
                &quot;expected {:?} to pass, got {:?}&quot;,
                formula,
                result
            );
            let mut actual = result.unwrap();
            actual.sort();
            expected.sort();
            assert_eq!(actual, expected);
        }
    }
}
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-54-encode-and-decode-base64"><a class="header" href="#kata-54-encode-and-decode-base64">Kata 54 (encode and decode base64)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>/**
 * encode and decode base64
*/
#[allow(dead_code)]
#[allow(unused)]
#[allow(non_snake_case)]
pub mod base64 {
    use std::os::unix::prelude::OsStrExt;
    use openssl::base64;
    pub fn encode(src: &amp;str) -&gt; String {
        base64::encode_block(src.as_bytes())
    }
    pub fn decode(s: &amp;str) -&gt; String {
        let decode_result = base64::decode_block(s);
        String::from_utf8(decode_result.unwrap()).clone().unwrap()
    }
    pub fn run() {
        let encode_result = encode(&quot;base64&quot;);
        println!(&quot;{:?}&quot;, encode_result); //&quot;YmFzZTY0&quot;
        let decode_result = decode(&amp;encode_result);
        println!(&quot;{:?}&quot;, decode_result); //&quot;base64&quot;
    }
}
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-55-count-of-positives--sum-of-negatives"><a class="header" href="#kata-55-count-of-positives--sum-of-negatives">Kata 55 (Count of positives / sum of negatives)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>/**
 *Count of positives / sum of negatives
 *https://www.codewars.com/kata/576bb71bbbcf0951d5000044/train/rust?collection=shi-yong-de-you-yi-si-de-ti
 */
#[allow(dead_code)]
#[allow(unused)]
#[allow(non_snake_case)]
pub mod count_positives_sum_negative {
    pub fn count_positives_sum_negatives(input: Vec&lt;i32&gt;) -&gt; Vec&lt;i32&gt; {
        let mut count = 0;
        let mut sum = 0;
        for item in input.iter() {
            if item &gt; &amp;0 {
                count += 1;
            } else {
                sum += item;
            }
        }
        if count &gt; 0 {
            vec![count, sum]
        } else {
            vec![]
        }
    }
    #[test]
    fn returns_expected() {
        let test_data1 = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15];
        let expected1 = vec![10, -65];
        assert_eq!(count_positives_sum_negatives(test_data1), expected1);
    }
}
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-56-encode-and-decode-to-aes-加密解密"><a class="header" href="#kata-56-encode-and-decode-to-aes-加密解密">Kata 56 (encode and decode to AES 加密解密)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>#[allow(dead_code)]
#[allow(unused)]
#[allow(non_snake_case)]
pub mod to_aes {
    pub fn run() {
        use libaes::Cipher;
        let arguments: Vec&lt;String&gt; = std::env::args().collect();
        // println!(&quot;{:?}&quot;, arguments);
        if arguments[1] == &quot;--text_encode&quot; || arguments[1] == &quot;-TE&quot; {
            let my_key = b&quot;dnropsdnropsdnro&quot;; // key is 16 bytes, i.e. 128-bit
            let plaintext = arguments[2].as_bytes();
            let iv = b&quot;dnropsdnropsdnro&quot;;

            // Create a new 128-bit cipher
            let cipher = Cipher::new_128(my_key);

            // Encryption
            let encrypted = cipher.cbc_encrypt(iv, plaintext);
            fn vec_to_string(v: Vec&lt;u8&gt;) -&gt; String {
                let mut re = String::new();
                for item in v.iter() {
                    re.push(*item as char);
                }
                re
            }
            println!(&quot;{:?}&quot;, vec_to_string(encrypted.to_vec()));

            // Decryption
            let decrypted = cipher.cbc_decrypt(iv, &amp;encrypted[..]);
        } else if arguments[1] == &quot;--text_decode&quot; || arguments[1] == &quot;-TD&quot; {
            let my_key = b&quot;dnropsdnropsdnro&quot;; // key is 16 bytes, i.e. 128-bit
            let plaintext = arguments[2].as_bytes();
            let iv = b&quot;dnropsdnropsdnro&quot;;

            // Create a new 128-bit cipher
            let cipher = Cipher::new_128(my_key);

            // Encryption
            let encrypted = cipher.cbc_encrypt(iv, plaintext);
            fn vec_to_string(v: Vec&lt;u8&gt;) -&gt; String {
                let mut re = String::new();
                for item in v.iter() {
                    re.push(*item as char);
                }
                re
            }
            // Decryption
            let decrypted = cipher.cbc_decrypt(iv, &amp;arguments[2].as_bytes()[..]);
            println!(&quot;{:?}&quot;, String::from_utf8(decrypted.to_vec())); //Ok(&quot;Alen_Andry&quot;)
        } else if arguments[1] == &quot;--binary_encode&quot; || arguments[1] == &quot;-BE&quot; {
            use std::fs::File;
            use std::io::prelude::*;
            use std::io::BufReader;
            let my_key = b&quot;dnropsdnropsdnro&quot;; // key is 16 bytes, i.e. 128-bit
            let mut file = File::open(&amp;arguments[2]).unwrap();
            // let mut buf_reader = BufReader::new(file);
            let mut file_copy = file.try_clone().unwrap();
            let mut contents = vec![];
            file_copy.read_to_end(&amp;mut contents);
            // let plaintext = arguments[2].as_bytes();
            let plaintext = contents.clone();
            let iv = b&quot;dnropsdnropsdnro&quot;;

            // Create a new 128-bit cipher
            let cipher = Cipher::new_128(my_key);

            // Encryptions
            let encrypted = cipher.cbc_encrypt(iv, &amp;plaintext);
            fn vec_to_string(v: Vec&lt;u8&gt;) -&gt; String {
                let mut re = String::new();
                for item in v.iter() {
                    re.push(*item as char);
                }
                re
            }
            let mut f = File::create(&amp;arguments[3]).unwrap();
            f.write_all(&amp;encrypted);
            // Decryption
            let decrypted = cipher.cbc_decrypt(iv, &amp;encrypted[..]);
        } else if arguments[1] == &quot;--binary_decode&quot; || arguments[1] == &quot;-BD&quot; {
            use std::fs::File;
            use std::io::prelude::*;
            use std::io::BufReader;
            let my_key = b&quot;dnropsdnropsdnro&quot;; // key is 16 bytes, i.e. 128-bit
            let mut file = File::open(&amp;arguments[2]).unwrap();
            // let mut buf_reader = BufReader::new(file);
            let mut file_copy = file.try_clone().unwrap();
            let mut contents = vec![];
            file_copy.read_to_end(&amp;mut contents);
            // let plaintext = arguments[2].as_bytes();
            let plaintext = contents.clone();
            let iv = b&quot;dnropsdnropsdnro&quot;;

            // Create a new 128-bit cipher
            let cipher = Cipher::new_128(my_key);

            // Encryptions
            let encrypted = cipher.cbc_encrypt(iv, &amp;plaintext);
            fn vec_to_string(v: Vec&lt;u8&gt;) -&gt; String {
                let mut re = String::new();
                for item in v.iter() {
                    re.push(*item as char);
                }
                re
            }
            // Decryption
            let decrypted = cipher.cbc_decrypt(iv, &amp;encrypted[..]);
            let mut f1 = File::create(&amp;arguments[3]).unwrap();
            f1.write_all(&amp;decrypted);
        }
    }
}
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-57-输出vec的所有不同顺序的子集"><a class="header" href="#kata-57-输出vec的所有不同顺序的子集">Kata 57 (输出vec的所有不同顺序的子集)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>#[allow(dead_code)]
#[allow(unused)]
#[allow(non_snake_case)]
pub mod premutaitions {
    pub fn run() {
        use itertools::Itertools;
        use std::borrow::Borrow;
        use std::cell::{RefCell, RefMut};
        //输出vec的所有不同顺序的子集
        let mut vec = Box::new(RefCell::new(vec![1, 2, 3]));
        let vec_len = vec.as_mut().get_mut().len();
        let mut re = vec![];
        for i in 1..vec_len + 1 {
            let vec_mut: &amp;mut Vec&lt;i64&gt; = vec.as_mut().get_mut();
            let mut new_vec = vec_mut.to_owned();
            let all_permumations = new_vec.into_iter().permutations(i).collect::&lt;Vec&lt;_&gt;&gt;();
            re.push(all_permumations);
        }
        println!(&quot;{:?}&quot;, re);
        //[[[1], [2], [3]], [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]], [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]]
    }
}
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-58-itertools-常用的function"><a class="header" href="#kata-58-itertools-常用的function">Kata 58 (itertools 常用的function)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>#[allow(dead_code)]
#[allow(unused)]
#[allow(non_snake_case)]
pub mod use_itertools {
    use itertools::*;
    use std::cell::{RefCell, RefMut};
    use std::collections::HashMap;
    pub fn run() {
        {
            //chain_vec 连接vec
            let chain_vec = chain(&amp;[1, 2, 3], &amp;[4, 6]).map(|x| *x).collect::&lt;Vec&lt;i32&gt;&gt;();
            eprintln!(&quot;{:?}&quot;, chain_vec);
            //enumerate
            for (index, item) in enumerate(&amp;chain_vec) {
                eprintln!(&quot;index:{}item:{}&quot;, index, item);
            }
        }

        {
            // find max  min
            let max_f32 = fold(&amp;[1., 2., 3.], 0., |a, &amp;b| f32::max(a, b));
            let min_f32 = fold(&amp;[1., 2., 3.], 0., |a, &amp;b| f32::min(a, b));
            eprintln!(&quot;{:?}&quot;, max_f32);
            eprintln!(&quot;{:?}&quot;, min_f32);
        }
        {
            //每一个位置后插入 另一个vec的元素
            let it1 = vec![1, 2, 3]
                .into_iter()
                .interleave(vec![10, 20, 30])
                .map(|x| x)
                .collect::&lt;Vec&lt;i32&gt;&gt;();
            eprintln!(&quot;{:?}&quot;, it1); //[1, 10, 2, 20, 3, 30]
        }
        {
            //每两个一起 存到vec![(1, 2), (1, 3), (1, 4)]
            let pit = vec![1, 2, 3, 4, 5, 6]
                .into_iter()
                .batching(|it| match it.next() {
                    None =&gt; None,
                    Some(x) =&gt; match it.next() {
                        None =&gt; None,
                        Some(y) =&gt; Some((x, y)),
                    },
                })
                .map(|x| x)
                .collect::&lt;Vec&lt;(i32, i32)&gt;&gt;();
            eprintln!(&quot;{:?}&quot;, pit); //[(0, 1), (2, 3), (4, 5), (6, 7)]
        }
        {
            //根据条件 分类vec
            let data1 = vec![1, 3, -2, -2, 1, 0, 1, 2];
            let mut data_grouped = Vec::new();
            for (key, group) in &amp;data1.into_iter().group_by(|elt| *elt &gt;= 0) {
                data_grouped.push((key, group.collect::&lt;Vec&lt;_&gt;&gt;()));
            }
            eprintln!(&quot;{:?}&quot;, data_grouped); //[(true, [1, 3]), (false, [-2, -2]), (true, [1, 0, 1, 2])]
        }
        {
            //每2个一起 存到vec 分别sum
            let data2 = vec![2, 3, 5, 6, -2, 0];
            let mut chunk_data = vec![];
            for chunk in &amp;data2.into_iter().chunks(2) {
                let mut ch = Box::new(RefCell::new(chunk));
                chunk_data.push((
                    ch.as_mut().get_mut().map(|x| x).collect::&lt;Vec&lt;_&gt;&gt;(),
                    ch.as_mut().get_mut().sum::&lt;i32&gt;(),
                ));
            }
            eprintln!(&quot;{:?}&quot;, chunk_data); //[([2, 3], 0), ([5, 6], 0), ([-2, 0], 0)]
        }
        {
            //每3个一起 存到tuple_vec
            let it1 = vec![1, 2, 3, 4].into_iter().tuple_windows::&lt;(_, _, _)&gt;();
            itertools::assert_equal(it1, vec![(1, 2, 3), (2, 3, 4)]);
            let it2 = (1..7).tuples::&lt;(_, _, _)&gt;();
            itertools::assert_equal(it2, vec![(1, 2, 3), (4, 5, 6)]);
        }
        {
            // 输出从小到大 第五个元素
            let numbers = vec![1, 5, 3, 0, 1, 2];
            let five_smallest = numbers.into_iter().k_smallest(5);
            eprintln!(&quot;{:?}&quot;, five_smallest);
        }
        {
            //Vec&lt;(i32, i32)&gt; to HashMap&lt;i32, Vec&lt;i32&gt;&gt;
            let data1 = vec![(0, 10), (2, 12), (3, 13), (0, 20), (3, 33), (2, 42)];
            let lookup1 = data1.into_iter().into_group_map();
            eprintln!(&quot;{:?}&quot;, lookup1);
        }
        {
            // Vec&lt;(i32, i32)&gt; to HashMap&lt;i32, Vec&lt;i32&gt;&gt; 根据第一个元素分类
            let data2 = vec![(0, 10), (2, 12), (3, 13), (0, 20), (3, 33), (2, 42)];
            let lookup2: HashMap&lt;u32, Vec&lt;(u32, u32)&gt;&gt; =
                data2.clone().into_iter().into_group_map_by(|a| a.0);
            eprintln!(&quot;{:?}&quot;, lookup2);
        }
        {
            //return 最大元素的位置
            let a = [-3_i32, 0, 1, 5, -10];
            assert_eq!(a.iter().position_max_by(|x, y| x.cmp(y)), Some(3));
        }
        {
            //return 最小元素位置
            let a = [-3, 0, 1, 5, -10];
            assert_eq!(a.iter().position_min(), Some(4));
        }
        {
            //输出vec的所有子集
            let sets = vec![1, 2].into_iter().powerset().collect::&lt;Vec&lt;_&gt;&gt;();
            eprintln!(&quot;{:?}&quot;, sets); //[[], [1], [2], [1, 2]]
        }
        {
            //找元素为位置
            let data = vec![1, 2, 3, 3, 4, 6, 7, 9];
            let positions = data
                .iter()
                .positions(|v| v % 2 == 0)
                .map(|x| x)
                .collect::&lt;Vec&lt;_&gt;&gt;();
            eprintln!(&quot;{:?}&quot;, positions);
        }
        {
            //drop some item 前后删除
            let init_front = vec![0, 3, 6, 9]
                .into_iter()
                .dropping(1)
                .map(|x| x)
                .collect::&lt;Vec&lt;_&gt;&gt;();
            eprintln!(&quot;{:?}&quot;, init_front); //[3, 6, 9]
            let init_back = vec![0, 3, 6, 9]
                .into_iter()
                .dropping_back(1)
                .map(|x| x)
                .collect::&lt;Vec&lt;_&gt;&gt;();
            eprintln!(&quot;{:?}&quot;, init_back); //[0, 3, 6]
        }
        {
            //求和 0-10
            let sum1 = (0..11).fold(0, |acc, y| acc + y);
            let sum2 = vec![1, 15, 10].into_iter().fold(0, |acc, y| acc + y);
            eprintln!(&quot;{:?},{:?}&quot;, sum1, sum2);
        }
        {
            //更新vec内部元素
            let input = vec![vec![1], vec![3, 2, 1]];
            let it = input
                .into_iter()
                .update(|mut v| v.push(0))
                .map(|x| x)
                .collect::&lt;Vec&lt;_&gt;&gt;();
            eprintln!(&quot;{:?}&quot;, it); // vec![vec![1, 0], vec![3, 2, 1, 0]]

            let vec = vec![1, 5, 6, 8];
            let new_vec = vec
                .into_iter()
                .update(|mut v| {
                    let mut vv = *v;
                    vv = vv * 10;
                    *v = vv;
                })
                .map(|x| x)
                .collect::&lt;Vec&lt;_&gt;&gt;();
            eprintln!(&quot;{:?}&quot;, new_vec); //[10, 50, 60, 80]
        }
        {
            //删除重复元素
            let data1 = vec![10, 20, 30, 20, 40, 10, 50];
            assert_equal(data1.into_iter().unique(), vec![10, 20, 30, 40, 50]);

            let data2 = vec![&quot;a&quot;, &quot;bb&quot;, &quot;aa&quot;, &quot;c&quot;, &quot;ccc&quot;];
            assert_equal(
                data2.into_iter().unique_by(|s| s.len()),
                vec![&quot;a&quot;, &quot;bb&quot;, &quot;ccc&quot;],
            );
        }
    }
}
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-59-snail-sort-矩阵蛇形遍历-iter-reverse"><a class="header" href="#kata-59-snail-sort-矩阵蛇形遍历-iter-reverse">Kata 59 (snail sort 矩阵蛇形遍历 .iter() reverse)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>/**
 * snail sort 矩阵蛇形遍历 .iter() reverse
 * https://www.codewars.com/kata/521c2db8ddc89b9b7a0000c1/train/rust
 */
#[allow(dead_code)]
#[allow(unused)]
#[allow(non_snake_case)]
pub mod snail_sort {
    pub fn get_matrix_edge(matrix: &amp;[Vec&lt;i32&gt;]) -&gt; Vec&lt;i32&gt; {
        // enjoy
        let mut re: Vec&lt;i32&gt; = vec![];
        let mut left = vec![];

        for (row_index, item_vec) in matrix.iter().enumerate() {
            if row_index == 0 {
                for (culmn_index, item_num) in item_vec.iter().enumerate() {
                    re.push(*item_num);
                }
            }
            if row_index != 0 {
                for (culmn_index, item_num) in item_vec.iter().enumerate() {
                    if culmn_index == item_vec.len() - 1 {
                        re.push(*item_num);
                    }
                }
            }
            if row_index == matrix.len() - 1 {
                let mut bottom = vec![];
                for (culmn_index, item_num) in item_vec.iter().enumerate() {
                    if culmn_index != item_vec.len() - 1 {
                        bottom.push(*item_num);
                    }
                }
                bottom.reverse();
                for bb in &amp;bottom {
                    re.push(*bb);
                }
            }
            for (culmn_index, item_num) in item_vec.iter().enumerate() {
                if culmn_index == 0 {
                    left.push(*item_num);
                }
            }
        }

        left.reverse();
        if left.len() &gt; 2 {
            left.remove(0);
            let len = left.len();
            left.remove(len - 1);
            for ll in &amp;left {
                re.push(*ll);
            }
        }

        re
    }
    pub fn split_matrix(matrix: &amp;[Vec&lt;i32&gt;], start_index: (usize, usize)) -&gt; Vec&lt;Vec&lt;i32&gt;&gt; {
        let mut re = Vec::new();
        let mut end_index: (usize, usize) = (0, 0);
        if matrix.len() &gt; 2 {
            end_index = (matrix.len() - 2, matrix.len() - 2);
            for (row_index, item_vec) in matrix.iter().enumerate() {
                let mut new_row = vec![];
                for (culmn_index, item_num) in item_vec.iter().enumerate() {
                    if culmn_index &gt;= start_index.1
                        &amp;&amp; culmn_index &lt;= end_index.1
                        &amp;&amp; row_index &gt;= start_index.0
                        &amp;&amp; row_index &lt;= end_index.0
                    {
                        new_row.push(*item_num);
                    }
                }
                if new_row.len() &gt; 0 {
                    re.push(new_row);
                }
            }
        }
        re
    }
    pub fn snail(matrix: &amp;[Vec&lt;i32&gt;]) -&gt; Vec&lt;i32&gt; {
        let mut re = Vec::new();
        re = get_matrix_edge(matrix);
        let mut new_matrix = split_matrix(matrix, (1, 1));
        let re1 = get_matrix_edge(&amp;new_matrix);
        for item in re1.iter() {
            re.push(*item);
        }
        while new_matrix.len() &gt;= 1 {
            new_matrix = split_matrix(&amp;new_matrix, (1, 1));
            let re1 = get_matrix_edge(&amp;new_matrix);
            for item in re1.iter() {
                re.push(*item);
            }
        }
        re
    }
    //other solution
    fn snail1(matrix: &amp;[Vec&lt;i32&gt;]) -&gt; Vec&lt;i32&gt; {
        let mut ret = Vec::new();
        if matrix.len() == 0 {
            return ret;
        }
        let mut width = matrix[0].len();
        let mut height = matrix.len();
        let mut cycle = 0;
        while width &gt; 0 &amp;&amp; height &gt; 0 {
            for x in cycle..width {
                ret.push(matrix[cycle][x]);
            }
            for y in cycle + 1..height {
                ret.push(matrix[y][width - 1]);
            }
            for x in (cycle..width - 1).rev() {
                ret.push(matrix[height - 1][x]);
            }
            for y in (cycle + 1..height - 1).rev() {
                ret.push(matrix[y][cycle]);
            }
            cycle += 1;
            width -= 1;
            height -= 1;
        }
        ret
    }

    pub fn run() {
        let square1 = &amp;[vec![1, 2, 3], vec![4, 5, 6], vec![7, 8, 9]];
        let square2 = &amp;[
            vec![1, 2, 3, 4],
            vec![5, 6, 7, 8],
            vec![9, 10, 11, 12],
            vec![13, 14, 15, 16],
        ];
        let square3 = &amp;[
            vec![543, 4, 207, 610, 748, 71, 813],
            vec![100, 61, 987, 541, 429, 798, 277],
            vec![63, 766, 838, 430, 271, 884, 274],
            vec![640, 765, 403, 676, 56, 233, 522],
            vec![335, 516, 590, 908, 150, 588, 221],
            vec![401, 522, 813, 89, 696, 173, 887],
            vec![844, 266, 636, 500, 493, 531, 334],
        ];
        println!(&quot;{:?}&quot;, snail1(square1));
        println!(&quot;{:?}&quot;, snail(square2));
        println!(&quot;{:?}&quot;, snail(square3));
    }
    #[cfg(test)]
    mod tests {
        use super::*;

        #[test]
        fn sample_test1() {
            let square = &amp;[vec![1, 2, 3], vec![4, 5, 6], vec![7, 8, 9]];
            let expected = vec![1, 2, 3, 6, 9, 8, 7, 4, 5];
            assert_eq!(snail(square), expected);
        }

        #[test]
        fn sample_test2() {
            let square = &amp;[vec![1, 2, 3], vec![8, 9, 4], vec![7, 6, 5]];
            let expected = vec![1, 2, 3, 4, 5, 6, 7, 8, 9];
            assert_eq!(snail(square), expected);
        }

        #[test]
        fn sample_test3() {
            let square: &amp;[Vec&lt;i32&gt;; 1] = &amp;[Vec::new()];
            let expected = Vec::new();
            assert_eq!(snail(square), expected, &quot;Failed with empty input&quot;);
        }

        #[test]
        fn sample_test4() {
            let square = &amp;[vec![1]];
            let expected = vec![1];
            assert_eq!(snail(square), expected);
        }
    }
}
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-60-use-scrcpy-connect-phone"><a class="header" href="#kata-60-use-scrcpy-connect-phone">Kata 60 (Use scrcpy connect phone)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>#[allow(dead_code)]
#[allow(unused)]
#[allow(non_snake_case)]
pub mod connect_phone {
    use std::process::Command;
    pub fn detect_phone() -&gt; Vec&lt;String&gt; {
        let result = Command::new(&quot;adb&quot;)
            .arg(&quot;devices&quot;)
            .output()
            .expect(&quot;command failed to start&quot;);
        let str_result_to_vec = std::str::from_utf8(&amp;result.stdout)
            .unwrap()
            .split(&quot;\n&quot;)
            .filter(|s| !s.is_empty())
            .collect::&lt;Vec&lt;_&gt;&gt;()
            .iter()
            .map(|s| s.to_string())
            .collect();
        str_result_to_vec
    }
    pub fn get_phone_ip() -&gt; String {
        let result = Command::new(&quot;adb&quot;)
            .arg(&quot;shell&quot;)
            .arg(&quot;ip&quot;)
            .arg(&quot;a&quot;)
            .output()
            .expect(&quot;command failed to start&quot;);
        let str_result_to_vec: Vec&lt;String&gt; = std::str::from_utf8(&amp;result.stdout)
            .unwrap()
            .split(&quot;\n&quot;)
            .filter(|s| !s.is_empty())
            .collect::&lt;Vec&lt;_&gt;&gt;()
            .iter()
            .map(|s| s.to_string())
            .collect();
        let mut re = String::from(&quot;phone is not connected or more than one device &quot;);
        for item in str_result_to_vec {
            if item.contains(&quot;192.&quot;) {
                re = item.trim().to_string().split(&quot;/&quot;).collect::&lt;Vec&lt;_&gt;&gt;()[0]
                    .to_string()
                    .split(&quot; &quot;)
                    .collect::&lt;Vec&lt;_&gt;&gt;()[1]
                    .to_string();
            }
        }
        re.to_string()
    }
    pub fn start_tcpip(port: &amp;str) -&gt; String {
        let result = Command::new(&quot;adb&quot;)
            .arg(&quot;tcpip&quot;)
            .arg(&quot;5555&quot;)
            .output()
            .expect(&quot;command failed to start&quot;);
        let str_result_to_vec: Vec&lt;String&gt; = std::str::from_utf8(&amp;result.stdout)
            .unwrap()
            .split(&quot;\n&quot;)
            .filter(|s| !s.is_empty())
            .collect::&lt;Vec&lt;_&gt;&gt;()
            .iter()
            .map(|s| s.to_string())
            .collect();
        let mut re = format!(&quot;can't start tcpip at {}&quot;, &amp;port);
        for item in str_result_to_vec {
            if item.contains(&amp;port) {
                re = item;
            }
        }
        re
    }
    pub fn connect_phone(ip_address: &amp;str, port: &amp;str) -&gt; String {
        let address = format!(&quot;{}:{}&quot;, ip_address, port);
        let result = Command::new(&quot;adb&quot;)
            .arg(&quot;connect&quot;)
            .arg(&amp;address)
            .output()
            .expect(&quot;command failed to start&quot;);
        let str_result_to_vec: Vec&lt;String&gt; = std::str::from_utf8(&amp;result.stdout)
            .unwrap()
            .split(&quot;\n&quot;)
            .filter(|s| !s.is_empty())
            .collect::&lt;Vec&lt;_&gt;&gt;()
            .iter()
            .map(|s| s.to_string())
            .collect();
        let mut re = format!(&quot;can't connect to :: {}&quot;, &amp;address);
        for item in str_result_to_vec {
            if item.contains(&quot;connected&quot;) &amp;&amp; !item.contains(&quot;failed&quot;) &amp;&amp; !item.contains(&quot;can't&quot;) {
                re = item;
                re.push_str(&quot; :: ready to run scrcpy&quot;);
            }
        }
        re
    }
    pub fn run_srcpy() -&gt; String {
        use std::thread;
        use std::time::{Duration, Instant};
        thread::sleep(Duration::from_secs(3));
        let result = Command::new(&quot;scrcpy&quot;)
            .spawn()
            .expect(&quot;can't connect open scrcpy&quot;);
        let mut re = format!(&quot;opening scrcpy&quot;);
        re
    }

    pub fn run() {
        let port = &quot;5555&quot;;
        let ip_address = get_phone_ip();
        println!(&quot;{:?}&quot;, detect_phone());
        println!(&quot;{:?}&quot;, get_phone_ip());
        println!(&quot;{:?}&quot;, start_tcpip(&amp;port));
        println!(&quot;{:?}&quot;, connect_phone(&amp;ip_address, &amp;port));
        println!(&quot;{:?}&quot;, run_srcpy());
    }
}
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-61-closest-and-smallest"><a class="header" href="#kata-61-closest-and-smallest">Kata 61 (Closest and Smallest)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>/**
 * Closest and Smallest
 * https://www.codewars.com/kata/5868b2de442e3fb2bb000119/train/rust
*/
#[allow(dead_code)]
#[allow(unused)]
#[allow(non_snake_case)]
pub mod closest_and_smallest {
    pub fn closest(s: &amp;str) -&gt; String {
        let mut s_vec: Vec&lt;i32&gt; = s
            .split(&quot; &quot;)
            .filter(|s| !s.is_empty())
            .collect::&lt;Vec&lt;_&gt;&gt;()
            .iter()
            .map(|s| s.parse::&lt;i32&gt;().unwrap())
            .collect();
        let mut s_weights: Vec&lt;i32&gt; = s
            .split(&quot; &quot;)
            .filter(|s| !s.is_empty())
            .collect::&lt;Vec&lt;_&gt;&gt;()
            .iter()
            .map(|s| {
                s.split(&quot;&quot;)
                    .filter(|s| !s.is_empty())
                    .collect::&lt;Vec&lt;_&gt;&gt;()
                    .iter()
                    .map(|s| s.parse::&lt;i32&gt;().unwrap())
                    .collect::&lt;Vec&lt;i32&gt;&gt;()
                    .iter()
                    .sum()
            })
            .collect();
        let mut collect_weights = Vec::new();
        for i in 0..s_weights.len() {
            collect_weights.push((s_weights[i], s_vec[i]));
        }
        let mut new_collect_weights = collect_weights.clone();
        new_collect_weights.sort_by(|a, b| a.0.partial_cmp(&amp;b.0).unwrap());
        fn find_closest(vec: &amp;mut Vec&lt;(i32, i32)&gt;) -&gt; (usize, usize, i32) {
            let mut adjacen_weights: Vec&lt;(usize, usize, i32)&gt; = vec![];
            for i in 0..vec.len() - 1 {
                adjacen_weights.push((i, i + 1, vec[i + 1].0 - vec[i].0));
            }
            adjacen_weights.sort_by(|a, b| a.2.partial_cmp(&amp;b.2).unwrap());
            adjacen_weights[0]
        }
        let closest_index = find_closest(&amp;mut new_collect_weights);
        let mut re = Vec::new();
        re.push(new_collect_weights[closest_index.0]);
        re.push(new_collect_weights[closest_index.1]);
        fn find_index(collect_weights: &amp;mut Vec&lt;(i32, i32)&gt;, target: i32) -&gt; usize {
            let mut re = 0;
            for i in 0..collect_weights.len() {
                if collect_weights[i].1 == target {
                    re = i;
                    break;
                }
            }
            re
        }
        let mut indexs = vec![];
        indexs.push(find_index(&amp;mut collect_weights, re[0].1));
        collect_weights.reverse();
        indexs.push(collect_weights.len() - 1 - find_index(&amp;mut collect_weights, re[1].1));
        let mut vec = vec![];
        vec.push(vec![re[0].0, indexs[0] as i32, re[0].1]);
        vec.push(vec![re[1].0, indexs[1] as i32, re[1].1]);
        let mut result = String::from(&quot;[&quot;);
        for item in vec.iter() {
            result.push_str(&quot;(&quot;);
            for item1 in item.iter() {
                result.push_str(&amp;format!(&quot;{:?},&quot;, item1));
            }
            result.push_str(&quot;)&quot;);
        }
        result.push_str(&amp;format!(&quot;]&quot;));
        let re = result.replace(&quot;,)&quot;, &quot;)&quot;);
        return re;
    }
    //other solution
    fn closest1(s: &amp;str) -&gt; String {
        use itertools::Itertools;
        fn weight(s: &amp;str) -&gt; u32 {
            s.chars().map(|c| c.to_digit(10).unwrap()).sum()
        }
        let (_, a, b) = s
            .trim()
            .split_whitespace()
            .enumerate()
            .map(|(i, x)| (weight(x) as i64, i, x))
            .sorted()
            .tuple_windows()
            .map(|(a, b)| ((a.0 - b.0).abs(), a, b))
            .min()
            .unwrap();
        format!(&quot;[({},{},{})({},{},{})]&quot;, a.0, a.1, a.2, b.0, b.1, b.2)
    }
    pub fn run() {
        let s = &quot;643181 268 211507 849 144916 396 568036 222 79436 641 506082 948 385502 626 631751 560 488490 210 538675 520 271288 641 137916 265 723201&quot;;
        let re = closest(s);
        println!(&quot;{:?}&quot;, re);
        let r = &quot;[(0,6,0)(0,7,0)]&quot;;
        assert_eq!(re, r.to_string());
    }
    #[cfg(test)]
    mod tests {
        use super::*;
        fn testing(s: &amp;str, exp: String) -&gt; () {
            let ans = closest(s);
            assert_eq!(ans, exp, &quot;Testing: {}&quot;, s);
        }
        #[test]
        fn basic_tests() {
            let mut s = &quot;456899 50 11992 176 272293 163 389128 96 290193 85 52&quot;; // [(13, 9, &quot;85&quot;), (14, 3, &quot;176&quot;)]
            testing(s, &quot;[(13,9,85)(14,3,176)]&quot;.to_string());
            s = &quot;239382 162 254765 182 485944 134 468751 62 49780 108 54&quot;; // &quot;[[8, 5, 134], [8, 7, 62]]&quot;;
            testing(s, &quot;[(8,5,134)(8,7,62)]&quot;.to_string());
            s = &quot;241259 154 155206 194 180502 147 300751 200 406683 37 57&quot;;
            let r = &quot;[(10,1,154)(10,9,37)]&quot;;
            testing(s, r.to_string());
        }
    }
}
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-62-解数独-nn的矩阵中每一行和列不能有重复的数字"><a class="header" href="#kata-62-解数独-nn的矩阵中每一行和列不能有重复的数字">Kata 62 (解数独 n*n的矩阵中每一行和列不能有重复的数字)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>#[allow(dead_code)]
#[allow(unused)]
#[allow(non_snake_case)]
pub mod sudoku_solver {
    struct Solution;
    impl Solution {
        pub fn solve_sudoku(board: &amp;mut Vec&lt;Vec&lt;char&gt;&gt;) {
            let mut empty_position = vec![];
            for i in 0..9 {
                for j in 0..9 {
                    if board[i][j] == '.' {
                        empty_position.push((i, j));
                        board[i][j] = '0';
                    }
                }
            }
            let position_len = empty_position.len();

            let mut loop_index = 0;
            while loop_index &lt; position_len {
                let (x, y) = empty_position[loop_index];

                if board[x][y] &lt; '9' {
                    board[x][y] = std::char::from_u32((board[x][y] as u32) + 1).unwrap();
                } else {
                    board[x][y] = '0';
                    loop_index -= 1;
                    continue;
                }
                if Solution::invalid(board, x, y) {
                    continue;
                }
                loop_index += 1;
            }
        }
        pub fn invalid(board: &amp;Vec&lt;Vec&lt;char&gt;&gt;, x: usize, y: usize) -&gt; bool {
            use std::collections::HashSet;
            let mut contain_table = HashSet::new();

            // validate line
            for i in 0..9 {
                let x1 = board[x][i];
                if x1 != '0' {
                    if contain_table.contains(&amp;x1) {
                        return true;
                    }
                    contain_table.insert(x1);
                }
            }
            contain_table.clear();

            // validate column

            for i in 0..9 {
                let x2 = board[i][y];
                if x2 != '0' {
                    if contain_table.contains(&amp;x2) {
                        return true;
                    }
                    contain_table.insert(x2);
                }
            }

            contain_table.clear();
            // validate box

            let i1 = x / 3;
            let i2 = y / 3;
            for i in 0..3 {
                for j in 0..3 {
                    let x3 = board[i1 * 3 + i][i2 * 3 + j];
                    if x3 != '0' {
                        if contain_table.contains(&amp;x3) {
                            return true;
                        }
                        contain_table.insert(x3);
                    }
                }
            }
            contain_table.clear();
            false
        }
    }
    #[cfg(test)]
    mod test {
        use super::*;

        #[test]
        fn test() {
            let mut sudoku = vec![
                vec!['5', '3', '.', '.', '7', '.', '.', '.', '.'],
                vec!['6', '.', '.', '1', '9', '5', '.', '.', '.'],
                vec!['.', '9', '8', '.', '.', '.', '.', '6', '.'],
                vec!['8', '.', '.', '.', '6', '.', '.', '.', '3'],
                vec!['4', '.', '.', '8', '.', '3', '.', '.', '1'],
                vec!['7', '.', '.', '.', '2', '.', '.', '.', '6'],
                vec!['.', '6', '.', '.', '.', '.', '2', '8', '.'],
                vec!['.', '.', '.', '4', '1', '9', '.', '.', '5'],
                vec!['.', '.', '.', '.', '8', '.', '.', '7', '9'],
            ];
            Solution::solve_sudoku(&amp;mut sudoku);

            let mut expected_solution = vec![
                vec!['5', '3', '4', '6', '7', '8', '9', '1', '2'],
                vec!['6', '7', '2', '1', '9', '5', '3', '4', '8'],
                vec!['1', '9', '8', '3', '4', '2', '5', '6', '7'],
                vec!['8', '5', '9', '7', '6', '1', '4', '2', '3'],
                vec!['4', '2', '6', '8', '5', '3', '7', '9', '1'],
                vec!['7', '1', '3', '9', '2', '4', '8', '5', '6'],
                vec!['9', '6', '1', '5', '3', '7', '2', '8', '4'],
                vec!['2', '8', '7', '4', '1', '9', '6', '3', '5'],
                vec!['3', '4', '5', '2', '8', '6', '1', '7', '9'],
            ];
            assert_eq!(expected_solution, sudoku);
        }

        #[test]
        fn test_invalid_method() {
            let mut expected_solution = vec![
                vec!['5', '3', '4', '6', '7', '8', '9', '1', '2'],
                vec!['6', '7', '2', '1', '9', '5', '3', '4', '8'],
                vec!['1', '9', '8', '3', '4', '2', '5', '6', '7'],
                vec!['8', '5', '9', '7', '6', '1', '4', '2', '3'],
                vec!['4', '2', '6', '8', '5', '3', '7', '9', '1'],
                vec!['7', '1', '3', '9', '2', '4', '8', '5', '6'],
                vec!['9', '6', '1', '5', '3', '7', '2', '8', '4'],
                vec!['2', '8', '7', '4', '1', '9', '6', '3', '5'],
                vec!['3', '4', '5', '2', '8', '6', '1', '7', '9'],
            ];
            for i in 0..9 {
                for j in 0..9 {
                    assert_eq!(false, Solution::invalid(&amp;expected_solution, i, j));
                }
            }
        }
    }
}
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-63-read-from-terminal-macroinput"><a class="header" href="#kata-63-read-from-terminal-macroinput">Kata 63 (Read from terminal macro,input!())</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>#[allow(unused_macros)]
macro_rules! input {
    () =&gt; {{
        let mut string = String::new();
        std::io::stdin().read_line(&amp;mut string).unwrap();
        string = string.to_string().trim().to_owned();
        string
    }};
}
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-64parse-string-进制转换"><a class="header" href="#kata-64parse-string-进制转换">Kata 64(parse string 进制转换)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>/**
 * pase string or decimal conversion
 */
#[allow(dead_code)]
#[allow(unused_variables)]
#[allow(unused)]
#[allow(non_snake_case)]
pub mod pase_string_decimal_conversion {
    pub fn run() {
        //Vec&lt;String&gt; to i64
        let mut vec = vec![];
        for i in 0..5 {
            vec.push(format!(&quot;{}&quot;, i));
        }
        let vec_to_i64: i64 = vec.into_iter().collect::&lt;String&gt;().parse().unwrap();
        assert_eq!(vec_to_i64, 1234);

        // String to i64
        let s = format!(&quot;444&quot;);
        let s_i64 = s.parse::&lt;i64&gt;().unwrap();
        assert_eq!(s_i64, 444);

        //split_i64 to Vec&lt;i64&gt;
        let split_i64 = format!(&quot;{}&quot;, 1234)
            .chars()
            .map(|x| i64::from(x.to_digit(10).unwrap()))
            .rev()
            .collect::&lt;Vec&lt;i64&gt;&gt;();

        assert_eq!(split_i64, vec![4, 3, 2, 1]);

        //char to i64
        let c: char = '5';
        let c_to_i64 = i64::from(c.to_digit(10).unwrap());
        assert_eq!(c_to_i64, 5);

        //&amp;str to Vec&lt;i64&gt;
        let s1: &amp;str = &quot;564&quot;;
        let c_to_i64 = s1
            .chars()
            .map(|x| i64::from(x.to_digit(10).unwrap()))
            .collect::&lt;Vec&lt;i64&gt;&gt;();
        assert_eq!(c_to_i64, vec![5, 6, 4]);

        //decimal conversion
        /**- ``, which uses the `Display` trait
        - `?`, which uses the `Debug` trait
        - `e`, which uses the `LowerExp` trait
        - `E`, which uses the `UpperExp` trait
        - `o`, which uses the `Octal` trait
        - `p`, which uses the `Pointer` trait
        - `b`, which uses the `Binary` trait
        - `x`, which uses the `LowerHex` trait
        - `X`, which uses the `UpperHex` trait
        */
        //十进制转化为其他进制
        //十进制to二进制
        let num = 454;
        let biynary_num = format!(&quot;{:b}&quot;, num);
        assert_eq!(biynary_num, format!(&quot;111000110&quot;));

        //十进制to八进制
        let octonary_num = format!(&quot;{:o}&quot;, num);
        assert_eq!(octonary_num, format!(&quot;706&quot;));

        //十进制to十六进制
        let hexadecimal_num = format!(&quot;{:x}&quot;, num);
        assert_eq!(hexadecimal_num, format!(&quot;1c6&quot;));

        //二进制转化为其他进制
        //二进制to十进制
        let num1 = &quot;100&quot;;
        fn binary_to_decimal(num: &amp;str) -&gt; String {
            let mut sum = 0;
            let mut vec = num
                .chars()
                .map(|x| i64::from(x.to_digit(10).unwrap()))
                .collect::&lt;Vec&lt;i64&gt;&gt;();
            for (index, item) in vec.iter().rev().enumerate() {
                sum += i64::pow(2, index as u32) * item;
            }
            format!(&quot;{}&quot;, sum)
        }
        //二进制转十进制结果
        let num_to_decimal = binary_to_decimal(num1);
        assert_eq!(num_to_decimal, format!(&quot;4&quot;));

        //二进制to八进制,先把二进制转十进制再转八进制
        let octonary_num = format!(&quot;{:o}&quot;, binary_to_decimal(&quot;1111&quot;).parse::&lt;i64&gt;().unwrap());
        assert_eq!(octonary_num, format!(&quot;17&quot;));

        //二进制to十六进制,先把二进制转十进制再转十六进制
        let hexadecimal_num = format!(&quot;{:x}&quot;, binary_to_decimal(&quot;1111&quot;).parse::&lt;i64&gt;().unwrap());
        assert_eq!(hexadecimal_num, format!(&quot;f&quot;));

        //八进制转化为其他进制
        //八进制to十进制
        fn octonary_to_decimal(num: &amp;str) -&gt; String {
            let mut sum = 0;
            let mut vec = num
                .chars()
                .map(|x| i64::from(x.to_digit(10).unwrap()))
                .collect::&lt;Vec&lt;i64&gt;&gt;();
            for (index, item) in vec.iter().rev().enumerate() {
                sum += i64::pow(8, index as u32) * item;
            }
            format!(&quot;{}&quot;, sum)
        }
        //八进制转十进制结果
        let num_to_decimal = octonary_to_decimal(&quot;1111&quot;);
        assert_eq!(num_to_decimal, format!(&quot;585&quot;));

        //八进制to二进制,先把八进制转十进制再转八进制
        let octonary_num = format!(&quot;{:b}&quot;, octonary_to_decimal(&quot;1111&quot;).parse::&lt;i64&gt;().unwrap());
        assert_eq!(octonary_num, format!(&quot;1001001001&quot;));

        //八进制to十六进制,先把八进制转十进制再转十六进制
        let hexadecimal_num = format!(&quot;{:x}&quot;, octonary_to_decimal(&quot;1111&quot;).parse::&lt;i64&gt;().unwrap());
        assert_eq!(hexadecimal_num, format!(&quot;249&quot;));

        //十六进制转化为其他进制
        //十六进制to十进制
        fn hexadecimal_to_decimal(num: &amp;str) -&gt; String {
            let mut sum = 0;
            let mut vec = num
                .chars()
                .map(|x| i64::from(x.to_digit(10).unwrap()))
                .collect::&lt;Vec&lt;i64&gt;&gt;();
            for (index, item) in vec.iter().rev().enumerate() {
                sum += i64::pow(16, index as u32) * item;
            }
            format!(&quot;{}&quot;, sum)
        }
        //十六进制转十进制结果
        let num_to_decimal = hexadecimal_to_decimal(&quot;1111&quot;);
        assert_eq!(num_to_decimal, format!(&quot;4369&quot;));

        //十六进制to二进制,先把十六进制转十进制再转八进制
        let octonary_num = format!(
            &quot;{:b}&quot;,
            hexadecimal_to_decimal(&quot;1111&quot;).parse::&lt;i64&gt;().unwrap()
        );
        assert_eq!(octonary_num, format!(&quot;1000100010001&quot;));

        //十六进制to八进制,先把十六进制转十进制再转十六进制
        let hexadecimal_num = format!(
            &quot;{:o}&quot;,
            hexadecimal_to_decimal(&quot;1111&quot;).parse::&lt;i64&gt;().unwrap()
        );
        assert_eq!(hexadecimal_num, format!(&quot;10421&quot;));
    }
}
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-65-rust-闭包"><a class="header" href="#kata-65-rust-闭包">Kata 65 (rust 闭包)</a></h2>
<pre><pre class="playground"><code class="language-rust">fn main() {
    //两个闭包共同分享一个值
    use std::sync::Mutex;
    let l = Box::leak(Box::new(Mutex::new(0.0)));
    let add = || {
        *l.lock().unwrap() += 1.0;
    };
    let min = || {
        *l.lock().unwrap() -= 1.0;
    };
    for _ in 0..10 {
        add();
        min();
    }
    println!(&quot;{:?}&quot;, *l.lock().unwrap()); //0.0
}</code></pre></pre>
<h2 id="kata-66-rust-append-data-to-file"><a class="header" href="#kata-66-rust-append-data-to-file">Kata 66 (Rust append data to file)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>//fsio = &quot;0.3.0&quot; add to Cargo.toml

	use fsio::{directory, file, path};
	use std::fs::File;
    use std::io::Write;
    use std::path::Path;
    use std::str;
    pub fn append(file_path: &amp;str, data: &amp;str) {
        let result = file::ensure_exists(file_path);
        if result.is_ok() {
            file::append_text_file(file_path, data);
        } else {
            File::create(file_path);
            file::append_text_file(file_path, data);
        }
    }
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-67-trait-object-dyn-vecvec-contains-diffrent-type"><a class="header" href="#kata-67-trait-object-dyn-vecvec-contains-diffrent-type">Kata 67 (Trait object dyn vec,(vec contains diffrent type))</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>/**
     * trait_object
     */
    pub mod trait_object {
        use std::fmt;
        use std::fmt::Write;

        pub fn run() {
            fn dyn_obj_vec() {
                //trait slug
                use dyn_clone::DynClone;

                pub trait Dyn_Vec: fmt::Display + fmt::Debug + DynClone {
                    fn slugify(&amp;self) -&gt; String;
                    fn tostring(&amp;self) -&gt; String;
                    fn prinln(&amp;self);
                }

                impl Dyn_Vec for String {
                    fn slugify(&amp;self) -&gt; String {
                        format!(&quot;{}&quot;, self.replace(&quot; &quot;, &quot;_&quot;))
                    }
                    fn tostring(&amp;self) -&gt; String {
                        format!(&quot;{}&quot;, self)
                    }
                    fn prinln(&amp;self) {
                        println!(&quot;{}&quot;, self);
                    }
                }
                impl Dyn_Vec for &amp;str {
                    fn slugify(&amp;self) -&gt; String {
                        format!(&quot;{}&quot;, self.to_string().replace(&quot; &quot;, &quot;_&quot;))
                    }
                    fn tostring(&amp;self) -&gt; String {
                        format!(&quot;{}&quot;, self)
                    }
                    fn prinln(&amp;self) {
                        println!(&quot;{}&quot;, self);
                    }
                }

                //int
                impl Dyn_Vec for i8 {
                    fn slugify(&amp;self) -&gt; String {
                        format!(&quot;{}&quot;, self.to_string().replace(&quot; &quot;, &quot;_&quot;))
                    }
                    fn tostring(&amp;self) -&gt; String {
                        format!(&quot;{}&quot;, self)
                    }
                    fn prinln(&amp;self) {
                        println!(&quot;{}&quot;, self);
                    }
                }
                impl Dyn_Vec for i16 {
                    fn slugify(&amp;self) -&gt; String {
                        format!(&quot;{}&quot;, self.to_string().replace(&quot; &quot;, &quot;_&quot;))
                    }
                    fn tostring(&amp;self) -&gt; String {
                        format!(&quot;{}&quot;, self)
                    }
                    fn prinln(&amp;self) {
                        println!(&quot;{}&quot;, self);
                    }
                }
                impl Dyn_Vec for i32 {
                    fn slugify(&amp;self) -&gt; String {
                        format!(&quot;{}&quot;, self.to_string().replace(&quot; &quot;, &quot;_&quot;))
                    }
                    fn tostring(&amp;self) -&gt; String {
                        format!(&quot;{}&quot;, self)
                    }
                    fn prinln(&amp;self) {
                        println!(&quot;{}&quot;, self);
                    }
                }
                impl Dyn_Vec for i64 {
                    fn slugify(&amp;self) -&gt; String {
                        format!(&quot;{}&quot;, self.to_string().replace(&quot; &quot;, &quot;_&quot;))
                    }
                    fn tostring(&amp;self) -&gt; String {
                        format!(&quot;{}&quot;, self)
                    }
                    fn prinln(&amp;self) {
                        println!(&quot;{}&quot;, self);
                    }
                }
                impl Dyn_Vec for i128 {
                    fn slugify(&amp;self) -&gt; String {
                        format!(&quot;{}&quot;, self.to_string().replace(&quot; &quot;, &quot;_&quot;))
                    }
                    fn tostring(&amp;self) -&gt; String {
                        format!(&quot;{}&quot;, self)
                    }
                    fn prinln(&amp;self) {
                        println!(&quot;{}&quot;, self);
                    }
                }
                //float
                impl Dyn_Vec for f32 {
                    fn slugify(&amp;self) -&gt; String {
                        format!(&quot;{}&quot;, self.to_string().replace(&quot; &quot;, &quot;_&quot;))
                    }
                    fn tostring(&amp;self) -&gt; String {
                        format!(&quot;{}&quot;, self)
                    }
                    fn prinln(&amp;self) {
                        println!(&quot;{}&quot;, self);
                    }
                }
                impl Dyn_Vec for f64 {
                    fn slugify(&amp;self) -&gt; String {
                        format!(&quot;{}&quot;, self.to_string().replace(&quot; &quot;, &quot;_&quot;))
                    }
                    fn tostring(&amp;self) -&gt; String {
                        format!(&quot;{}&quot;, self)
                    }
                    fn prinln(&amp;self) {
                        println!(&quot;{}&quot;, self);
                    }
                }
                //the same type of vec slice impl trait
                //slice item  is a thing has implmented trait slug
                fn same(h: &amp;[impl Dyn_Vec]) {
                    //is short cut of same1()
                    for s in h {
                        println!(&quot;{}&quot;, s.tostring());
                    }
                }
                //slice item  is a thing has implmented trait slug and need to be the same type
                fn same1&lt;H: Dyn_Vec&gt;(h: &amp;[H]) {
                    for s in h {
                        s.prinln();
                    }
                }
                same(&amp;[&quot;a&quot;, &quot;b&quot;, &quot;c&quot;]);
                same1(&amp;[format!(&quot;s0&quot;), format!(&quot;s1&quot;), format!(&quot;s2&quot;)]);

                //diffrent type of vec slice impl trait
                //slice item  is a thing has implmented trait slug canbe diffrent type
                //vec contain diffrent type
                pub fn new_Dyn_Vec() -&gt; Vec&lt;Box&lt;dyn Dyn_Vec&gt;&gt; {
                    vec![Box::new(&quot;default&quot;) as Box&lt;dyn Dyn_Vec&gt;]
                }
                let mut Dyn_Vec: Vec&lt;Box&lt;dyn Dyn_Vec&gt;&gt; = new_Dyn_Vec();
                Dyn_Vec.push(Box::new(&quot;151515&quot;));
                Dyn_Vec.push(Box::new(15));
                Dyn_Vec.push(Box::new(String::from(&quot;string&quot;)));
                Dyn_Vec.push(Box::new(1.02));
                //println dyn obj
                fn println_Dyn_Vec(h: &amp;[Box&lt;dyn Dyn_Vec&gt;]) {
                    for s in h {
                        println!(&quot;{}&quot;, s.tostring());
                    }
                }

                println_Dyn_Vec(&amp;Dyn_Vec);

                println!(&quot;{:?}&quot;, Dyn_Vec);
                //impl Clone for trait object
                dyn_clone::clone_trait_object!(Dyn_Vec);
                #[derive(Clone)]
                struct Each_Dyn_Vec(Box&lt;dyn Dyn_Vec&gt;);
                let first = Dyn_Vec[0].clone();
                println!(&quot;{}&quot;, first);

                // fast way to implment object trait
                use thin_trait_object::*;
                #[thin_trait_object]
                trait Addable {
                    fn add(&amp;self, other: &amp;str) -&gt; String;
                }
                impl Addable for String {
                    fn add(&amp;self, other: &amp;str) -&gt; String {
                        format!(&quot;{}{}&quot;, self, other)
                    }
                }
                impl Addable for &amp;str {
                    fn add(&amp;self, other: &amp;str) -&gt; String {
                        format!(&quot;{}{}&quot;, self, other)
                    }
                }
                impl Addable for Vec&lt;i32&gt; {
                    fn add(&amp;self, other: &amp;str) -&gt; String {
                        let mut v = self.clone();
                        let re = match other.parse::&lt;i32&gt;() {
                            Ok(r) =&gt; {
                                v.push(r);
                                v
                            }
                            Err(r) =&gt; v,
                        };
                        format!(&quot;{:?}&quot;, re)
                    }
                }
                impl Addable for Vec&lt;String&gt; {
                    fn add(&amp;self, other: &amp;str) -&gt; String {
                        let mut v = self.clone();
                        v.push(other.to_string());
                        format!(&quot;{:?}&quot;, v)
                    }
                }
                //move occurs because value has type `String`, which does not implement the `Copy` trait
                //when this error ust yhe trait
                #[thin_trait_object]
                trait Cloneable {
                    fn clone_by_index(&amp;self, index: usize) -&gt; String;
                }
                impl Cloneable for Vec&lt;String&gt; {
                    fn clone_by_index(&amp;self, index: usize) -&gt; String {
                        let s = self.to_owned();
                        format!(&quot;{}&quot;, &amp;s[index])
                    }
                }

                let s1 = BoxedAddable::new(&quot;String&quot;.to_string()).add(&quot;add&quot;);
                let s2 = BoxedAddable::new(&quot;&amp;str&quot;).add(&quot;add&quot;);
                let s3 = &quot;ok&quot;.add(&quot;add&quot;);
                let s4 = vec![15, 2].add(&quot;15151&quot;); //[15, 2, 15151]
                let s5 = vec![format!(&quot;ok&quot;)].add(&quot;add str&quot;); //[15, 2, 15151]
                let s6 = vec![format!(&quot;ok&quot;)].clone_by_index(0);
                println!(&quot;{}&quot;, s1);
                println!(&quot;{}&quot;, s2);
                println!(&quot;{}&quot;, s3);
                println!(&quot;{}&quot;, s4);
                println!(&quot;{}&quot;, s5);
                println!(&quot;{}&quot;, s6);
            }
            dyn_obj_vec();
        }
    }
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-68-conversion_between_str_string"><a class="header" href="#kata-68-conversion_between_str_string">Kata 68 (conversion_between_str_string)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub mod conversion_between_str_string {
       pub fn run() {
           pub fn to_str(s: impl AsRef&lt;str&gt;) -&gt; impl AsRef&lt;str&gt; {
               s
           }
           pub fn tostring1(s: impl AsRef&lt;str&gt; + std::fmt::Debug + std::fmt::Display) -&gt; String {
               format!(&quot;{}&quot;, s)
           }
           trait Tostring: ToString + std::fmt::Debug + std::fmt::Display {
               fn to_string(&amp;self) -&gt; String;
           }
           pub fn tostring(s: &amp;dyn Tostring) -&gt; String {
               format!(&quot;{}&quot;, s)
           }
           impl&lt;T: std::fmt::Display + ?Sized + std::fmt::Debug&gt; Tostring for T {
               fn to_string(&amp;self) -&gt; String {
                   let mut buf = String::new();
                   //for use std::fmt::Formatter::new need to add #![feature(fmt_internals)] to top of main.rs
                   let mut formatter = unsafe { std::fmt::Formatter::new(&amp;mut buf) };
                   // Bypass format_args!() to avoid write_str with zero-length strs
                   std::fmt::Display::fmt(self, &amp;mut formatter)
                       .expect(&quot;a Display implementation returned an error unexpectedly&quot;);
                   buf
               }
           }
           assert_eq!(to_str(&quot;&amp;str&quot;).as_ref(), &quot;&amp;str&quot;);
           assert_eq!(to_str(format!(&quot;String&quot;)).as_ref(), &quot;String&quot;);
           assert_eq!(tostring(&amp;format!(&quot;String&quot;)).as_ref(), format!(&quot;String&quot;));
           assert_eq!(tostring(&amp;&quot;&amp;str&quot;).as_ref(), format!(&quot;&amp;str&quot;));
           assert_eq!(tostring(&amp;15).as_ref(), format!(&quot;15&quot;));
           assert_eq!(tostring(&amp;15.5).as_ref(), format!(&quot;15.5&quot;));
           assert_eq!(tostring(&amp;15.56_f64).as_ref(), format!(&quot;15.56&quot;));
       }
   }
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-kata-69-vec-clone-get-item"><a class="header" href="#kata-kata-69-vec-clone-get-item">Kata Kata 69 (Vec<String> clone get item)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>trait Cloneable {
        fn clone_by_index(&amp;self, index: usize) -&gt; String;
    }
    impl Cloneable for Vec&lt;String&gt; {
        fn clone_by_index(&amp;self, index: usize) -&gt; String {
            let s = self.to_owned();
            format!(&quot;{}&quot;, &amp;s[index])
        }
    }
    let s: Vec&lt;String&gt; = vec![format!(&quot;1&quot;), format!(&quot;2&quot;), format!(&quot;3&quot;)];
    let f0 = s.clone_by_index(0);
    let f1 = s.clone_by_index(0);
    println!(&quot;{}&quot;, f0);
    println!(&quot;{}&quot;, f1);
<span class="boring">}</span></code></pre></pre>
<h2 id="kata-70-cross-compile-cros-compile-cfg-compile"><a class="header" href="#kata-70-cross-compile-cros-compile-cfg-compile">Kata 70 (Cross compile cros compile cfg compile)</a></h2>
<pre><pre class="playground"><code class="language-rust">fn main() {
    #[cfg(not(target_os = &quot;linux&quot;))]
    println!(&quot;not linux&quot;);

    #[cfg(target_os = &quot;linux&quot;)]
    println!(&quot;linux&quot;);

    #[cfg(target_os = &quot;windows&quot;)]
    println!(&quot;windows&quot;);

    #[cfg(target_os = &quot;macos&quot;)]
    println!(&quot;macos&quot;);

    #[cfg(target_os = &quot;ios&quot;)]
    println!(&quot;ios&quot;);

    #[cfg(target_os = &quot;android&quot;)]
    println!(&quot;android&quot;);

    #[cfg(target_os = &quot;fuchsia&quot;)]
    println!(&quot;fuchsia&quot;);

    #[cfg(target_os = &quot;freebsd&quot;)]
    println!(&quot;freebsd&quot;);
}</code></pre></pre>
<h2 id="kata-71-gnome_sort"><a class="header" href="#kata-71-gnome_sort">Kata 71 (gnome_sort)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>fn gnome_sort&lt;T: Ord&gt;(v: &amp;mut Vec&lt;T&gt;) {
    let mut i = 0;
    while i &lt; v.len() {
        if i == 0 || v[i - 1].le(&amp;v[i]) {
            i += 1;
        } else {
            v.swap(i - 1, i);
            i -= 1;
        }
    }
}
<span class="boring">}</span></code></pre></pre>
<h2 id="kata72-where-my-anagrams-at"><a class="header" href="#kata72-where-my-anagrams-at">Kata72 (where my anagrams at)</a></h2>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>/**
 * Where my anagrams at?
 * https://www.codewars.com/kata/523a86aa4230ebb5420001e1/train/rust
 * What is an anagram? Well, two words are anagrams of each other if they both contain the same letters. For example:
'abba' &amp; 'baab' == true
'abba' &amp; 'bbaa' == true
'abba' &amp; 'abbba' == false
'abba' &amp; 'abca' == false
元素种类相同,出现次数相同=&gt;true
元素种类不相同,出现次数不相同=&gt;false

Write a function that will find all the anagrams of a word from a list. You will be given two inputs a word and an array with words. You should return an array of all the anagrams or an empty array if there are none. For example:
anagrams('abba', ['aabb', 'abcd', 'bbaa', 'dada']) =&gt; ['aabb', 'bbaa']
anagrams('racer', ['crazer', 'carer', 'racar', 'caers', 'racer']) =&gt; ['carer', 'racer']
anagrams('laser', ['lazing', 'lazy',  'lacer']) =&gt; []
Note for Go
For Go: Empty string slice is expected when there are no anagrams found.
 */
#[allow(dead_code)]
#[allow(unused_variables)]
#[allow(unused)]
#[allow(non_snake_case)]
pub mod where_my_anagrams_at {
    fn anagrams(word: &amp;str, words: &amp;[String]) -&gt; Vec&lt;String&gt; {
        // your code here
        fn is_same(word1: &amp;str, word2: &amp;str) -&gt; bool {
            fn ordered_count(sip: &amp;str) -&gt; Vec&lt;(char, i32)&gt; {
                use std::collections::BTreeMap;
                let sip = sip.to_owned();
                let set_sip = sip.clone();
                let mut arr_sip: Vec&lt;char&gt; = set_sip.chars().collect();
                arr_sip.sort();
                arr_sip.reverse();
                let mut bmap = BTreeMap::new();
                for x in arr_sip {
                    bmap.insert(x, count_x_in_str(&amp;sip, x));
                }
                fn count_x_in_str(sip: &amp;str, target: char) -&gt; i32 {
                    let mut c: i32 = 0;
                    for x in sip.chars() {
                        if target == x {
                            c += 1;
                        }
                    }
                    return c;
                }
                // bmap to tuple vec
                fn convert_bmap_to_vec(bmap: BTreeMap&lt;char, i32&gt;) -&gt; Vec&lt;(char, i32)&gt; {
                    let mut vec = vec![];
                    for (v, k) in &amp;bmap {
                        vec.push((v.to_owned(), k.to_owned()));
                    }
                    return vec;
                }
                return convert_bmap_to_vec(bmap);
            }
            if ordered_count(word1).eq(&amp;ordered_count(word2)) {
                return true;
            } else {
                return false;
            }
        }
        let mut re: Vec&lt;String&gt; = vec![];
        for item in words.iter() {
            if is_same(word, item) {
                re.push(item.to_owned());
            }
        }
        re
    }
    //other solution
    fn anagrams1(word: &amp;str, words: &amp;[String]) -&gt; Vec&lt;String&gt; {
        use itertools::Itertools;
        let cs = word.chars().sorted().collect_vec();
        words
            .iter()
            .filter(|s| s.chars().sorted().collect_vec() == cs)
            .cloned()
            // .map(|s|s.to_owned()) //the same to cloned()
            .collect()
    }
    pub fn run() {}

    #[cfg(test)]
    mod tests {
        use super::*;
        #[test]
        fn sample_tests() {
            do_test(&quot;abba&quot;, &amp;[&quot;aabb&quot;, &quot;abcd&quot;, &quot;bbaa&quot;, &quot;dada&quot;], &amp;[&quot;aabb&quot;, &quot;bbaa&quot;]);

            do_test(
                &quot;racer&quot;,
                &amp;[&quot;crazer&quot;, &quot;carer&quot;, &quot;racar&quot;, &quot;caers&quot;, &quot;racer&quot;],
                &amp;[&quot;carer&quot;, &quot;racer&quot;],
            );
        }

        fn do_test(word: &amp;str, words: &amp;[&amp;str], exp: &amp;[&amp;str]) {
            let words: Vec&lt;String&gt; = words.iter().map(|w| w.to_string()).collect();
            let expected: Vec&lt;String&gt; = exp.iter().map(|w| w.to_string()).collect();
            let got = anagrams(word, &amp;words);
            assert_eq!(
                got, expected,
                &quot;Failed with word: \&quot;{}\&quot;\nwords: {:#?}&quot;,
                word, words
            );
        }
    }
}
<span class="boring">}</span></code></pre></pre>

                    </main>

                    <nav class="nav-wrapper" aria-label="Page navigation">
                        <!-- Mobile navigation buttons -->
                            <a rel="prev" href="../../posts/leetcode/rust_leetcode.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                                <i class="fa fa-angle-left"></i>
                            </a>

                            <a rel="next" href="../../posts/leetcode/swift_codewar.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                                <i class="fa fa-angle-right"></i>
                            </a>

                        <div style="clear: both"></div>
                    </nav>
                </div>
            </div>

            <nav class="nav-wide-wrapper" aria-label="Page navigation">
                    <a rel="prev" href="../../posts/leetcode/rust_leetcode.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                        <i class="fa fa-angle-left"></i>
                    </a>

                    <a rel="next" href="../../posts/leetcode/swift_codewar.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                        <i class="fa fa-angle-right"></i>
                    </a>
            </nav>

        </div>



        <script>
            window.playground_line_numbers = true;
        </script>

        <script>
            window.playground_copyable = true;
        </script>

        <script src="../../ace.js"></script>
        <script src="../../editor.js"></script>
        <script src="../../mode-rust.js"></script>
        <script src="../../theme-dawn.js"></script>
        <script src="../../theme-tomorrow_night.js"></script>

        <script src="../../elasticlunr.min.js"></script>
        <script src="../../mark.min.js"></script>
        <script src="../../searcher.js"></script>

        <script src="../../clipboard.min.js"></script>
        <script src="../../highlight.js"></script>
        <script src="../../book.js"></script>

        <!-- Custom JS scripts -->
        <script src="../../src/js/custom.js"></script>


    </div>
    </body>
</html>
